python生成式:列表、字典、集合

python的3类生成式:

列表生成式

字典生成式

集合生成式


 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的行,所以

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的键值对

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)

输出:集合

原文地址:https://www.cnblogs.com/andy9468/p/10855284.html