python:列表生成器

今天来聊聊python的列表生成器python

最简单的:code

 

[x for x in range(10)]

获得的结果是:对象

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]字符串

 

稍微复杂一点的:it

 

[x for x in 'abcdefg']

结果:生成器

['a', 'b', 'c', 'd', 'e', 'f', 'g']co

没错,这个能够把字符串转成单个字符的列表
 字典

msg='abcdefg'
print([x for x in msg])

结果:字符

['a', 'b', 'c', 'd', 'e', 'f', 'g']生成

 

总之,这样能够把一个可迭代对象拆开,好比:

 

这样(字典):

 

msg={1:'abc',2:'bbc'}
print([x for x in msg.items()])

结果:

相关文章
相关标签/搜索