Python推导式(列表推导式、元组推导式、字典推导式和集合推导式)

列表表达式

a_range = range(10)
# 对a_range执行for表达式
a_list = [x * x for x in a_range]
# a_list集合包含10个元素
print(a_list)

# 嵌套生成
e_list = [[x, y, z] for x in range(5) for y in range(4) for z in range(6)]
# e_list列表包含120个元素
print(e_list)

元祖表达式

a = (x for x in range(1,10))
print(a)
<generator object <genexpr> at 0x0000020BAD136620>

print(tuple(a))
(1, 2, 3, 4, 5, 6, 7, 8, 9)

字典表达式

olddict={'C语言中文网': 6, 'c.biancheng.net': 15}
newdict = {v: k for k, v in olddict.items() if v>10}
print(newdict)

集合表达式

tupledemo = (1,1,2,3,4,5,6,6)
setnew = {x**2 for x in tupledemo if x%2==0}
print(setnew)
posted @ 2020-09-24 09:58  程序猿-悟空  阅读(279)  评论(0编辑  收藏  举报