土薯工具 Toolshu.com 登录 用户注册

Python 列表推导式与内置函数速查:写更少的代码,做更多的事

原创 作者:bhnw 于 2026-04-09 13:12 发布 1次浏览 收藏 (0)

写了三行能写一行的代码,是技术问题

看到别人的 Python 代码,短短一行完成了你写五行才能做的事,不是炫技,是真的更简洁、更 Pythonic。

这篇文章整理列表推导式和最常用的内置函数,每个都配可以直接拿走的代码片段。


列表推导式

列表推导式(List Comprehension)是 Python 最具代表性的语法之一,用一行代替 for 循环构建列表。

基本语法:

[表达式 for 元素 in 可迭代对象 if 条件]

基础:替代 for 循环

# 传统写法
squares = []
for x in range(10):
    squares.append(x ** 2)

# 列表推导式
squares = [x ** 2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

加上条件过滤

# 只取偶数的平方
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]

# 过滤列表中的空字符串
words = ["hello", "", "world", "", "python"]
clean = [w for w in words if w]
# ["hello", "world", "python"]

字符串处理

names = ["alice", "bob", "charlie"]

# 首字母大写
capitalized = [name.capitalize() for name in names]
# ["Alice", "Bob", "Charlie"]

# 过滤长度大于3的名字并转大写
result = [name.upper() for name in names if len(name) > 3]
# ["ALICE", "CHARLIE"]

嵌套列表推导式(二维数组展平)

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# 展平二维列表
flat = [x for row in matrix for x in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

字典推导式和集合推导式

# 字典推导式
words = ["apple", "banana", "cherry"]
word_lengths = {word: len(word) for word in words}
# {"apple": 5, "banana": 6, "cherry": 6}

# 集合推导式(自动去重)
nums = [1, 2, 2, 3, 3, 3]
unique = {x ** 2 for x in nums}
# {1, 4, 9}

生成器表达式:省内存的版本

列表推导式会一次性把所有元素放进内存,数据量大时改用生成器表达式(把 [] 换成 ()):

# 列表推导式:立即生成所有元素
total = sum([x ** 2 for x in range(1000000)])

# 生成器表达式:逐个生成,省内存
total = sum(x ** 2 for x in range(1000000))  # 直接省掉外层[]

最常用的内置函数

Python 内置了大量高质量函数,学会用这些,很多需要自己手写的逻辑可以省掉。

map():对每个元素应用函数

nums = [1, 2, 3, 4, 5]

# 每个数平方
squares = list(map(lambda x: x ** 2, nums))
# [1, 4, 9, 16, 25]

# 字符串列表转整数
str_nums = ["1", "2", "3"]
int_nums = list(map(int, str_nums))
# [1, 2, 3]

很多情况下列表推导式比 map 更可读,但 map 在配合现成函数时更简洁。

filter():过滤元素

nums = [1, -2, 3, -4, 5, -6]

# 只保留正数
positives = list(filter(lambda x: x > 0, nums))
# [1, 3, 5]

# filter(None, ...) 过滤所有假值(0、None、空字符串等)
mixed = [0, 1, "", "hello", None, 42]
truthy = list(filter(None, mixed))
# [1, "hello", 42]

zip():并行遍历多个列表

names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]

# 配对
pairs = list(zip(names, scores))
# [("Alice", 95), ("Bob", 87), ("Charlie", 92)]

# 配合 for 循环
for name, score in zip(names, scores):
    print(f"{name}: {score}")

# 解压(zip 的逆操作)
unzipped_names, unzipped_scores = zip(*pairs)

enumerate():遍历时带索引

fruits = ["apple", "banana", "cherry"]

# 不用 range(len(...))
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry

# 从1开始编号
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")

sorted()sort():排序

nums = [3, 1, 4, 1, 5, 9, 2, 6]

# sorted() 返回新列表,不改变原列表
asc = sorted(nums)           # [1, 1, 2, 3, 4, 5, 6, 9]
desc = sorted(nums, reverse=True)  # [9, 6, 5, 4, 3, 2, 1, 1]

# sort() 原地排序,返回 None
nums.sort()

# 按自定义规则排序
words = ["banana", "apple", "cherry", "date"]
by_length = sorted(words, key=len)       # 按长度
by_second = sorted(words, key=lambda w: w[1])  # 按第二个字母

# 按字典的某个字段排序
users = [{"name": "Bob", "age": 30}, {"name": "Alice", "age": 25}]
by_age = sorted(users, key=lambda u: u["age"])

any()all():批量逻辑判断

nums = [1, 2, 3, 4, 5]

# any():至少一个为真
has_even = any(x % 2 == 0 for x in nums)   # True
has_neg = any(x < 0 for x in nums)          # False

# all():全部为真
all_positive = all(x > 0 for x in nums)     # True
all_even = all(x % 2 == 0 for x in nums)    # False

# 实际用途:验证表单字段是否全部填写
fields = {"name": "Alice", "email": "alice@example.com", "age": 28}
is_complete = all(fields.values())   # True(所有值都是真值)

min()max():最值

nums = [3, 1, 4, 1, 5, 9]
print(min(nums))   # 1
print(max(nums))   # 9

# 带 key 参数
words = ["banana", "apple", "cherry"]
shortest = min(words, key=len)   # "apple"
longest = max(words, key=len)    # "banana" 或 "cherry"

# 找字典列表中某字段的最值
users = [{"name": "Bob", "age": 30}, {"name": "Alice", "age": 25}]
youngest = min(users, key=lambda u: u["age"])
# {"name": "Alice", "age": 25}

sum():求和

nums = [1, 2, 3, 4, 5]
print(sum(nums))          # 15
print(sum(nums, 100))     # 115(从100开始累加)

# 计算嵌套列表的总和
matrix = [[1, 2], [3, 4], [5, 6]]
total = sum(sum(row) for row in matrix)   # 21

isinstance():类型判断

x = 42

# 判断单个类型
print(isinstance(x, int))       # True
print(isinstance(x, str))       # False

# 同时判断多个类型
print(isinstance(x, (int, float)))   # True(是数字就行)

# 实际用途:函数参数校验
def process(data):
    if not isinstance(data, (list, tuple)):
        raise TypeError(f"期望列表或元组,得到 {type(data).__name__}")
    return [x * 2 for x in data]

round()abs()divmod()

# round():四舍五入
round(3.14159, 2)   # 3.14
round(3.5)          # 4(Python 3 是银行家舍入,偶数优先)
round(2.5)          # 2

# abs():绝对值
abs(-5)    # 5
abs(-3.14) # 3.14

# divmod():同时得到商和余数
q, r = divmod(17, 5)   # q=3, r=2

一行代码速查

收藏这几个常用的单行技巧:

# 列表去重(保留顺序)
seen = set()
unique = [x for x in lst if not (x in seen or seen.add(x))]

# 或者不需要保序时
unique = list(set(lst))

# 列表展平(一层)
flat = [x for sublist in nested for x in sublist]

# 统计元素出现次数
from collections import Counter
counts = Counter(["a", "b", "a", "c", "b", "a"])
# Counter({"a": 3, "b": 2, "c": 1})

# 字典合并(Python 3.9+)
merged = dict1 | dict2

# 交换两个变量
a, b = b, a

# 检查列表是否为空
if not my_list:
    print("列表为空")

想把这些片段直接跑起来验证效果,粘到 Python 在线运行工具 里,Python 3.12 环境,改完即看结果,不用装任何东西。

发现周边 发现周边
评论区

加载中...