python列表生成式和元组生成式

列表生成式,生成列表

list_a = [1, 2, 3]
list_c = list((4, 5, 6)) # list_c == [4, 5, 6]
list_d = [i for i in list_a]  # list_d == [1, 2, 3]
list_e = [i*j for i in list_a for j in list_c] # list_e == [4,5,6,10,12,12,15,18]
list_f = [i*j for i,j in zip(list_a,list_c)] # list_f == [4, 10, 18]
list_g = [i for i in list_a if i%2 == 0] # list_g == [2]

元组生成式生成一个生成器对象,通过for或者next遍历,遍历后,原生成器对象就不存在了

t1=(i*i for i in range(10))
print t1.next()
print t1.next()
tuple1=tuple(t1)
print tuple1
#结果:
0
1
(4, 9, 16, 25, 36, 49, 64, 81)

 

t2=(i for i in range(10))
for i in t2:
    print i,
tuple2=tuple(t2)
print tuple2
#结果
0 1 2 3 4 5 6 7 8 9 ()

 

posted @ 2019-02-28 13:14  我有一个桃花源  阅读(5034)  评论(0编辑  收藏  举报