python的3类生成式:

列表生成式

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

字典生成式

集合生成式

 1、python列表生成式

my_data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("my_data: %s" % my_data)

rows_to_keep = [row for row in my_data if row[2] > 5]
print("rows_to_keep: %s" % rows_to_keep)

输出:

保留每行中索引位置2的值大于5的行,所以

python生成式:列表、字典、集合 随笔 第1张

 

 

2、python字典生成式

my_dict = {"a": 1, "b": 2, "c": 3}
print(my_dict)
my_results = {key: value for key, value in my_dict.items() if value > 2}
print(my_results)

输出:值大于2的键值对

python生成式:列表、字典、集合 随笔 第2张

 

3、python集合生成式

my_data = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (7, 8, 9)]
print("my_data: %s" % my_data)

set_of_tuples1 = {x for x in my_data}
print("set_of_tuples1: %s" % set_of_tuples1)

set_of_tuples2 = set(my_data)
print("set_of_tuples2: %s" % set_of_tuples2)

输出:集合

python生成式:列表、字典、集合 随笔 第3张

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄