Comprehension
一句话解释
comprehension 是 compact 语法 for 创建 列表, dicts, or 设置 从 iterable in 单个 表达式.
用大白话说
A comprehension is a concise way to create a collection by transforming and/or filtering items from an iterable. It replaces a multi-line for loop with a single readable expression.
List comprehension: [expr for 项 in iterable 如果条件] Dict comprehension: {键: 值 for 项 in iterable} Set comprehension: {expr for 项 in iterable}
The optional 如果 clause filters which items are included. Comprehensions are more Pythonic and often faster than equivalent for loops, but very complex comprehensions should be split into regular loops for readability.
示例
# List comprehension
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# With filter
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
# Dict comprehension
word_len = {w: len(w) for w in ["cat", "dog", "bird"]}
print(word_len) # {'cat': 3, 'dog': 3, 'bird': 4}Comprehensions 创建 集合 concisely 使用 表达式, 循环, and 可选 筛选.
常见混淆
容易混淆的对象: lambda
关键区别: comprehension 创建 集合 通过 transforming 项. lambda 创建 anonymous 函数. Comprehensions produce 数据; lambdas produce callable 函数.
相关术语
相关资源
相关课程
- 列表 Comprehensions
Comprehensions.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。