列表生成式和字典生成式
2018-09-02 本文已影响2人
陆_志东
列表生成式
a = [x for x in range(5)]
print(a)
>>[0, 1, 2, 3, 4]
b = [x for x in range(0,10,2)]
print(b)
>>[0, 2, 4, 6, 8]
c = [x for x in range(10) if x%2 == 0]
print(c)
>>[0, 2, 4, 6, 8]
d = [x for x in [y for y in range(10)] if x % 2 == 0]
print(d)
>>[0, 2, 4, 6, 8]
e = [(x,y) for x in range(3) for y in range(3)] #双重嵌套for循环
print(e)
>>[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
f = [x.lower() for x in ["A","B","C"]]
print(f)
>>['a', 'b', 'c']
字典生成式
g = {x:y for x,y in [("a",1),("b",2),("c",3)]}
print(g)
>>{'a': 1, 'b': 2, 'c': 3}