一行写列表(List Comprehensions)

发布: (2026年4月20日 GMT+8 10:59)
5 分钟阅读
原文: Dev.to

Source: Dev.to

介绍

你可以使用循环在 Python 中构建列表,但列表推导式让你能够在一行可读的代码中完成同样的工作。

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = []

for n in numbers:
    squares.append(n * n)

print(squares)
# Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

使用列表推导式得到相同的结果:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [n * n for n in numbers]

print(squares)
# Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

语法

像阅读句子一样从左到右阅读推导式:

[expression for variable in iterable]
  • expression – 你想在新列表中得到的内容(计算、函数调用等)。
  • variable – 循环变量(例如 n)。
  • iterable – 任意可迭代对象(列表、range、字符串等)。

添加过滤条件

[expression for variable in iterable if condition]

if 子句仅保留 conditionTrue 的项。

示例

简单转换

names = ["alex", "priya", "sam", "jordan"]
upper_names = [name.upper() for name in names]
print(upper_names)
# Output: ['ALEX', 'PRIYA', 'SAM', 'JORDAN']
lengths = [len(name) for name in names]
print(lengths)
# Output: [4, 5, 3, 6]
numbers = range(1, 6)
doubled = [n * 2 for n in numbers]
print(doubled)
# Output: [2, 4, 6, 8, 10]

过滤

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(evens)
# Output: [2, 4, 6, 8, 10]
scores = [45, 92, 78, 61, 34, 88, 55, 97]
passing = [s for s in scores if s >= 60]
print(passing)
# Output: [92, 78, 61, 88, 97]

同时转换和过滤

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_evens = [n * n for n in numbers if n % 2 == 0]
print(squared_evens)
# Output: [4, 16, 36, 64, 100]

处理字符串

sentence = "Hello World"
letters = [char for char in sentence if char != " "]
print(letters)
# Output: ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
words = ["  hello  ", "  world  ", "  python  "]
cleaned = [w.strip() for w in words]
print(cleaned)
# Output: ['hello', 'world', 'python']

字典推导式

names = ["Alex", "Priya", "Sam"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)
# Output: {'Alex': 4, 'Priya': 5, 'Sam': 3}
scores = {"Alex": 92, "Priya": 58, "Sam": 75, "Jordan": 44}
passing = {name: score for name, score in scores.items() if score >= 60}
print(passing)
# Output: {'Alex': 92, 'Sam': 75}

何时不使用列表推导式

如果逻辑变得复杂,普通循环更清晰:

# 难以阅读的列表推导式
result = [process(transform(validate(x))) for x in data if check_one(x) and check_two(x)]

# 使用循环更清晰
result = []
for x in data:
    if check_one(x) and check_two(x):
        validated = validate(x)
        transformed = transform(validated)
        result.append(process(transformed))

经验法则: 仅在能一眼看懂的情况下才使用列表推导式。

练习

创建一个文件 comprehensions_practice.py,仅使用推导式(comprehensions),对给定的数据执行以下任务:

temperatures_c = [0, 10, 20, 30, 40, 100]
words = ["Python", "is", "great", "for", "AI", "and", "ML"]
students = [
    {"name": "Alex", "score": 88},
    {"name": "Priya", "score": 52},
    {"name": "Sam", "score": 76},
    {"name": "Jordan", "score": 91},
    {"name": "Lisa", "score": 43}
]
  1. 将每个温度转换为华氏度(F = C * 9/5 + 32),并将结果存入列表。
  2. 构建一个包含长度大于三个字符的单词的列表。
  3. 提取仅包含学生姓名的列表。
  4. 提取分数 ≥ 60(及格)的学生姓名列表。
  5. 构建一个字典,将每个学生的姓名映射到其分数。
0 浏览
Back to Blog

相关文章

阅读更多 »