Python 生成式

博客主要介绍了Python中的生成式,包括列表生成式、集合生成式和字典生成式,这些生成式是Python编程中重要的特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

列表生成式

1. [x for x in data if condition]
此处if主要起条件判断作用,data数据中只有满足if条件的才会被留下,最终生成一个数据列表。
2. [exp1 if condition else exp2 for x in data]
此处if…else主要起赋值作用。当data中的数据满足if条件时,将其做exp1处理,否则按照exp2处理,最终生成一个数据列表。

一、
列表生成式即List Comprehensions,
是Python内置的非常简单却强大的可以用来创建list的生成式。
例如:
要生成list  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 可以用  range(1, 11)
二、
[x * x for x in range(1, 11)]
运行结果
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
三、
可以在后面加条件。
[x * x for x in range(1, 11) if x % 2 == 0]
运行结果
[4, 16, 36, 64, 100]
四、
可以放多重循环。
[m + n for m in 'ABC' for n in 'XYZ']
运行结果:
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
五、
结合字典使用
d = {'x': 'A', 'y': 'B', 'z': 'C' }
print([k + '=' + v for k, v in d.items()])
运行结果:
['x=A', 'y=B', 'z=C']

集合生成式

与列表生成式类似。
my_data = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (7, 8, 9)]
set_of_tuples1 = {x for x in my_data}
print("Output #2 (set comprehension): {}".format(set_of_tuples1))
set_of_tuples2 = set(my_data)  # 内置的set函数更好
print("Output #3 (set function): {}".format(set_of_tuples2))
运行结果:
Output #2 (set comprehension): {(4, 5, 6), (7, 8, 9), (1, 2, 3)}
Output #3 (set function): {(4, 5, 6), (7, 8, 9), (1, 2, 3)}

字典生成式

与列表生成式类似。
例一、
my_dictionary = {'customer1': 7, 'customer2': 9, 'customer3': 11}
my_results = {key: value for key, value in my_dictionary.items() if value > 10}
print("Output #3 (dictionary comprehension): {}".format(my_results))
运行结果:
Output #3 (dictionary comprehension): {'customer3': 11}
例二、
import random
stuInfo = {'student' + str(i):random.randint(60,100) for i in range(20)}
print({name:score for name,score in stuInfo.items() if score > 90})
运行结果:
{'student0': 95, 'student1': 97, 'student2': 93, 'student6': 92, 'student14': 99, 'student16': 92, 'student17': 98}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值