惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Hacker News: Ask HN
Hacker News: Ask HN
N
News and Events Feed by Topic
Forbes - Security
Forbes - Security
The Last Watchdog
The Last Watchdog
TaoSecurity Blog
TaoSecurity Blog
Schneier on Security
Schneier on Security
SecWiki News
SecWiki News
V
Vulnerabilities – Threatpost
Project Zero
Project Zero
O
OpenAI News
W
WeLiveSecurity
Security Archives - TechRepublic
Security Archives - TechRepublic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
H
Hacker News: Front Page
Cisco Talos Blog
Cisco Talos Blog
Spread Privacy
Spread Privacy
Help Net Security
Help Net Security
P
Privacy & Cybersecurity Law Blog
K
Kaspersky official blog
S
Security @ Cisco Blogs
Latest news
Latest news
AWS News Blog
AWS News Blog
U
Unit 42
Martin Fowler
Martin Fowler
阮一峰的网络日志
阮一峰的网络日志
S
Secure Thoughts
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Know Your Adversary
Know Your Adversary
Scott Helme
Scott Helme
博客园 - 司徒正美
B
Blog RSS Feed
C
Check Point Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
D
Docker
Google Online Security Blog
Google Online Security Blog
Jina AI
Jina AI
aimingoo的专栏
aimingoo的专栏
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Last Week in AI
Last Week in AI
月光博客
月光博客
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
SegmentFault 最新的问题
NISL@THU
NISL@THU
T
The Blog of Author Tim Ferriss
C
Cisco Blogs
Attack and Defense Labs
Attack and Defense Labs
小众软件
小众软件

博客园 - 百衲本

Centos7 副本集模式部署 MongoDB centos7部署Nacos集群模式 centos7 yum快速安装clickhouse单机版 k8s高可用部署Seata kubernetes中pod磁盘占用排查 jumpserver V3 终端常用操作 Python 的可迭代对象、迭代器对象与生成器 python email模块自动化操作邮件 python yagmail 模块自动化操作邮件 python自动化操作PDF 国内企业邓白氏编码免费申请流程 Python psutil模块 免费公共API调用清单 Python pathlib 模块 容器网络故障排查:从 ping 到 tcpdump 的全链路思路 systemd详解 APP性能指标 Linux 上禁用 USB 存储设备 线上故障的排查清单,运维小哥拿走不谢!
Python 列表生成式、字典生成式与生成器表达式
百衲本 · 2025-09-30 · via 博客园 - 百衲本

1. 列表生成式 (List Comprehension)

语法:[expression for item in iterable if condition]

示例:

1.基本示例
# 创建平方数列表
squares = [x**2 for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

# 创建偶数列表
evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8]

2.带条件的列表生成式 # 过滤出长度大于3的单词 words = ['apple', 'cat', 'dog', 'elephant', 'bat'] long_words = [word for word in words if len(word) > 3] print(long_words) # ['apple', 'elephant'] # 处理字符串列表 names = ['alice', 'bob', 'charlie'] capitalized = [name.title() for name in names] print(capitalized) # ['Alice', 'Bob', 'Charlie'] 3.多重循环 # 创建坐标列表 coordinates = [(x, y) for x in range(3) for y in range(2)] print(coordinates) # [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)] # 矩阵转置 matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] transposed = [[row[i] for row in matrix] for i in range(3)] print(transposed) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

2. 字典生成式 (Dictionary Comprehension)

语法:{key_expression: value_expression for item in iterable if condition}

示例:

1.基本示例
# 创建数字平方字典
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 转换列表为字典
fruits = ['apple', 'banana', 'cherry']
fruit_dict = {fruit: len(fruit) for fruit in fruits}
print(fruit_dict)  # {'apple': 5, 'banana': 6, 'cherry': 6}


2.带条件的字典生成式
# 只保留值大于2的项
numbers = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered = {k: v for k, v in numbers.items() if v > 2}
print(filtered)  # {'c': 3, 'd': 4}

# 键值转换
original = {'a': 1, 'b': 2, 'c': 3}
swapped = {v: k for k, v in original.items()}
print(swapped)  # {1: 'a', 2: 'b', 3: 'c'}


3.处理字符串
# 创建字符索引字典
text = "hello"
char_index = {char: index for index, char in enumerate(text)}
print(char_index)  # {'h': 0, 'e': 1, 'l': 2, 'l': 3, 'o': 4}

# 大小写转换
data = {'Name': 'Alice', 'Age': 25, 'City': 'Beijing'}
lowercase_keys = {k.lower(): v for k, v in data.items()}
print(lowercase_keys)  # {'name': 'Alice', 'age': 25, 'city': 'Beijing'}

3. 生成器表达式 (Generator Expression)

语法:(expression for item in iterable if condition)

示例

1.基本示例
# 创建生成器表达式
squares_gen = (x**2 for x in range(5))
print(squares_gen)  # <generator object <genexpr> at 0x...>

# 使用生成器
for num in squares_gen:
    print(num, end=" ")  # 0 1 4 9 16
print()

# 生成器只能使用一次
squares_gen = (x**2 for x in range(3))
print(list(squares_gen))  # [0, 1, 4]
print(list(squares_gen))  # [] - 已经耗尽


2. 处理大文件时节省内存
# 假设有一个大文件,我们想统计行数
lines = (line for line in open('large_file.txt', 'r') if 'error' in line)
error_count = sum(1 for _ in lines)
print(f"错误行数: {error_count}")

3.链式处理数据
numbers = (x for x in range(10))
squared = (x**2 for x in numbers)
filtered = (x for x in squared if x % 2 == 0)
result = list(filtered)
print(result)  # [0, 4, 16, 36, 64]