2013-02-15 184 views
0

如何创建一个函数来以这种方式迭代我的列表。 似乎简单,但即时通讯卡...通过嵌套列表进行迭代

myList= [[1,2,3], [4,5,6], [7,8,9]] 

    def name(myList): 
     somework.. 

    newList = [[1,4,7]. [ 2,5,8], [3,6,9]] 
+0

你是否想要一种转换你的列表的方法? – Floris 2013-02-15 04:27:26

+0

[Python中的移调/解压缩函数]可能的重复(http://stackoverflow.com/questions/19339/a-transpose-unzip-function-in-python) – JBernardo 2013-02-15 05:08:33

回答

3
In [3]: zip(*myList) 
Out[3]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)] 

,如果你特别希望清单

In [4]: [list(x) for x in zip(*myList)] 
Out[4]: [[1, 4, 7], [2, 5, 8], [3, 6, 9]] 

zip函数查找更多的细节在this

+0

你能产生一个相同的函数吗? – BAI 2013-02-15 04:29:42

+0

@BAI - 在编辑之前,这里有一个不必要的list-comp。它已被删除。 – mgilson 2013-02-15 04:30:29

2

zip是你想要的+论证拆包。这很棒。我喜欢把它看作python的内置转置。

newList = zip(*myList) 

这实际上给你tuple可迭代(python3.x)或list(python2.x),但是这对于大多数来说已经足够好。