2017-04-10 53 views

回答

3

你应该使用这里zip

>>> lst =[[1,2,'a'],[3,4,'b'],[5,6,'c'],[7,8,'d']] 

# Python 2.7 
>>> result = zip(*lst) 
>>> result 
[(1, 3, 5, 7), (2, 4, 6, 8), ('a', 'b', 'c', 'd')] 

在Python 3+,zip返回发生器对象。为了得到价值list,你必须明确地类型强制转换为:

# In Python3+ 
>>> list(zip(*lst)) 
[(1, 3, 5, 7), (2, 4, 6, 8), ('a', 'b', 'c', 'd')] 
0
listLen,listElemLen = len(lst), len(lst[0]) 
res = [] 
for i in range(listElemLen): 
    temp = [] 
    for j in range(listLen): 
     temp.append(lst[j][i]) 
    res.append(temp) 
print(res) #[[1,3,5,7],[2,4,6,8],['a','b','c','d']] 
+0

我相信缩进错误悄悄在你的代码,当你它复制到答案,'res.append (temp)'应该在内部for循环之外。 –

+0

@ juanpa.arrivillaga啊。是。谢谢你指出。编辑。 – Geetanjali

相关问题