Python 简化for循环:列表,集合与字典生成式

列表生成式

# 使用列表生成选择特定的行
my_data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rows_to_keep = [row for row in my_data if row[2] > 5]
print("Output #1 (list comprehension): {}".format(rows_to_keep))

列表生成式的意义是:对于my_data中的每一行,如果这行中索引位置2的值大于5,则保留这行。

集合生成式

#使用集合生成式在列表中选择出一组唯一的元组
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))

字典生成式

#使用字典生成式选择特定的键-值对
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))

 

posted @ 2018-03-06 16:56  乐高先生  阅读(6966)  评论(0编辑  收藏  举报