>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = [x for x in i for i in a]
>>> b
[1, 1, 2, 2, 3, 3]
>>> c = [x for x in i for i in a]
>>> c
[4, 4, 5, 5, 6, 6]
如何解释上面代码的运行结果?
一般的得到的结果是[4, 4, 5, 5, 6, 6],但是偶然会得到[1, 1, 2, 2, 3, 3],这是为什么呢?
如何把[[1, 2, 3], [4, 5, 6]]用列表推导成[1,2,3,4,5,6]的形式?
b = [x for x in i for i in a]
在我的解釋器中無法運作.flatten
在stack overflow 上有詳細的討論, 上面的方法被發現是最快的,沒想到更簡潔的方法。
在 [5] 中:b = [x for i in a for x in i]
在[6]中:b
輸出[6]: [1, 2, 3, 4, 5, 6]
三維圖的
在[7]: aa = [[[1], [2], [3]], [[4], [5], [6]]]
在[8]中:b = [y for i in aa for x in i for y in x]
在[9]中:b
輸出[9]: [1, 2, 3, 4, 5, 6]