今天來聊聊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()])
結果: