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))

 

转载于:https://www.cnblogs.com/legoxz/p/8515308.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值