列表生成式

现在有个需求,看列表[0,1,2,3,4,5,6,7,8,9],要求你把列表里每个值都加1,你怎么实现?你可能会想到两种方法。

二逼青年版

>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> b = []
>>> for i in a:
...     b.append(i+1)
...
>>> b
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a = b
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

普通青年版

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for index,i in enumerate(a):
    a[index] +=1

print(a)

文艺青年版

>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a = map(lambda x:x+1,a)
>>> a
<map object at 0x0000025486AE20B8>
>>> for i in a:
...     print(i)
...
1
2
3
4
5
6
7
8
9
10

其实,还有一种方法

装逼青年版

>>> a = [i+1 for i in range(0,10)]  #列表生成式
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

列表生成式还可以进行三元运算

>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = [i if i<5 else i*i for i in a]
>>> a
[0, 1, 2, 3, 4, 25, 36, 49, 64, 81]

列表还可以讲字符串拆进列表

>>> a = 'alexli'
>>> a = [i for i in a]
>>> a
['a', 'l', 'e', 'x', 'l', 'i']

列表生成式用一行操作修改列表中数据,元组也是可以的,别的不行。