python的列表生成式

列表生成式,即通过生成式简洁创建list列表,可任意通过一行代码实现

原来我们生成list可以用list(range(0, 5))
>>> list(range(0,5))
[0, 1, 2, 3, 4]
如果要生成[1x1,2x2, 3x3, …, 10x10]可以用循环
>>> for n in range(0, 10):
...     L.append(n * n)
...
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>
但是这样的循环方式过于繁琐,此时,我们就可以使用列表生成式,代码会非常简洁。
>>> [n * n for n in range(0, 10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>
n * n是当前遍历到元素n执行的动作, 注意最外层是方括号[], 代表是list
我们还可以加上过滤条件
>>> [n * n for n in range(0, 10) if n % 2 == 0]
[0, 4, 16, 36, 64] #打印偶数
>>>
>>> [s.lower() for s in ['Ac', 'dDDD', 123] if(isinstance(s, str))]
['ac', 'dddd'] #把字符串变成小写,过滤掉不是字符串的元素,因为不是字符串调用lower()函数会报错
>>> [s.lower() for s in ['Ac', 'dDDD', 123]]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'
>>>
还可以使用两层、三层循环,三层比较少用
>>> [a + b for a in 'ABCD' for b in 'abcd']
['Aa', 'Ab', 'Ac', 'Ad', 'Ba', 'Bb', 'Bc', 'Bd', 'Ca', 'Cb', 'Cc', 'Cd', 'Da', '
Db', 'Dc', 'Dd']
>>>

猜你喜欢

转载自blog.csdn.net/qq_29144091/article/details/81286940