列表推导式、字典推导式、集合推导式

一、列表推导式

例一:

multiples = [i for i in range(30) if i % 3 is 0]
print(multiples)
# Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

例二:

def squared(x):
    return x*x
multiples = [squared(i) for i in range(30) if i % 3 is 0]
print multiples
#  Output: [0, 9, 36, 81, 144, 225, 324, 441, 576, 729]

2、使用()生成generator

将俩表推导式的[]改成()即可得到生成器。

multiples = (i for i in range(30) if i % 3 is 0)
print(type(multiples))
#  Output: <type 'generator'>

二、字典推导式

# 因为key是唯一的,所以最后value都是1
dict_a = {key: value for key in 'python' for value in range(2)}
print(dict_a)

# 可以根据键来构造值
dict_b = {key: key * key for key in range(6)}
print(dict_b)

# 遍历一个有键值关系的可迭代对象
list_phone = [('HUAWEI', '华为'), ('MI', '小米'), ('OPPO', 'OPPO'), ('VIVO', 'VIVO')]
dict_c = {key: value for key, value in list_phone}
print(dict_c)


{'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{'HUAWEI': '华为', 'MI': '小米', 'OPPO': 'OPPO', 'VIVO': 'VIVO'}

三,集合推导式

# 遍历一个可迭代对象生成集合
set_a = {value for value in '有人云淡风轻,有人负重前行'}
print(set_a)

{'负', '前', '重', '有', '云', ',', '行', '风', '人', '淡', '轻'}
 
原文地址:https://www.cnblogs.com/lvchengda/p/12618223.html