Python 推导式是一种独特的数据处理方式,可以从一个数据序列构建另一个新的数据序列的结构体。 Python 有以下数据结构的推导式: - 列表(list)推导式 - 字典(dict)推导式 - 集合(set)推导式 - 元组(tuple)推导式
列表推导式语法如下:
[表达式 for 变量 in 列表]
[out_exp_res for out_exp in input_list]
#或者
[表达式 for 变量 in 列表 if 条件]
[out_exp_res for out_exp in input_list if condition]
实例:
# -*- coding: utf-8 -*-
# @Time : 2022/3/30 10:36
# @File : express.py
# @Software : PyCharm
fruits = ['grape', 'watermelon', 'apple', 'banana', 'orange']
#过滤掉长度小于或等于5的水果字符串,并将剩下的转换成大写字母
new_fruits = [f.upper() for f in fruits if len(f) > 5]
print(new_fruits)
#计算 100 以内可以被 7 整除的整数
multiples = [i for i in range(100) if i % 7 == 0]
print(multiples)
运行结果:
['WATERMELON', 'BANANA', 'ORANGE']
[0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98]
字典推导式语法如下:
{ key_expr: value_expr for value in collection }
#或
{ key_expr: value_expr for value in collection if condition }
实例:
# -*- coding: utf-8 -*-
# @Time : 2022/3/30 10:45
# @File : dic_express.py
# @Software : PyCharm
#计算10以内的每个数的立方值
dict = {x: x**3 for x in range(10)}
print(dict)
运行结果:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}
集合推导式语法如下:
{ expression for item in Sequence }
#或
{ expression for item in Sequence if conditional }
实例:
# -*- coding: utf-8 -*-
# @Time : 2022/3/30 10:49
# @File : set_express.py
# @Software : PyCharm
#过滤出字符串中的小写字母
a = {x for x in 'HelloWorld' if ord(x) not in range(ord('A'),ord('Z'))}
print(a)
运行结果:
{'r', 'd', 'e', 'l', 'o'}
元组推导式语法如下:
(expression for item in Sequence )
#或
(expression for item in Sequence if conditional )
实例:
# -*- coding: utf-8 -*-
# @Time : 2022/3/30 11:01
# @File : tuple_express.py
# @Software : PyCharm
#生成一个包含数字 1~10 的元组
a = (x for x in range(1,11))
print(a)
# 使用 tuple() 函数,可以直接将生成器对象转换成元组
print(tuple(a))
运行结果:
<generator object <genexpr> at 0x000002566D5FECE0>
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
推导式在Python中有许多其他用途,除了之前提到的数据转换和筛选数据外,还包括但不限于以下几种用途:
你可以使用列表推导式将多个列表的元素进行组合,生成新的列表结构。例如,你可以使用嵌套的列表推导式来创建一个二维列表的转置。
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transposed) # 输出: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
列表推导式不仅限于简单的算术运算或条件判断,你还可以在其中执行更复杂的操作,如函数调用、属性访问等。
# 假设有一个Person类,具有name和age属性
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = [Person("Alice", 25), Person("Bob", 30), Person("Charlie", 35)]
names = [person.name for person in people]
print(names) # 输出: ['Alice', 'Bob', 'Charlie']
你可以使用列表推导式来循环执行某个函数,并将结果收集到一个列表中。
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
squares = [square(x) for x in numbers]
print(squares) # 输出: [1, 4, 9, 16, 25]
虽然这不是列表推导式的直接用途,但你可以结合字典推导式(Dictionary Comprehensions)来实现这些转换。
例如,将一个包含元组的列表转换为字典:
items = [(1, 'apple'), (2, 'banana'), (3, 'cherry')]
dictionary = {key: value for key, value in items}
print(dictionary) # 输出: {1: 'apple', 2: 'banana', 3: 'cherry'}