python 列表推导式、列表生成式

使用列表推导式、生成式可以快速的构造出列表:

最简单的:

x = '12045'
>>> lst = [i for i in x]
>>>lst
['1', '2', '0', '4', '5']

带 if 条件的

x = '12045'
>>> lst = [i for i in x if i != '0']
>>>lst
['1', '2', '4', '5']

带 if···else···条件的

x = '12045'
>>> lst = [i  if i != '0' else 'xxx' for i in x]
>>>lst
['1', '2', 'xxx', '4', '5']

如果不准备对生成的列表进行修改, 只是访问用,则可以改为列表生成器:

最简单的:

x = '12045'
>>> lst = (i for i in x)
>>>lst
<generator object <genexpr> at 0x027BA738>

猜你喜欢

转载自www.cnblogs.com/wangyueyouyi/p/9558999.html