2015-05-07 127 views
1

我有一些Python列表,嵌套列表命名otherElem它看起來像:嵌套列表迭代

otherElem=[[list1],[list2],...[list_n]] 

我需要的是創建將執行一些操作的新名單(這是j.Mirror是無關緊要的,可以是任何東西)並創建一個新的列表,以維護先前列表的順序和格式。我試過這個,但沒有成功。我在編程全新的,遺憾的錯字(如果有的話)

for i in otherElem: 
     for j in i: 
      j=j.Mirror(mirPlane) 
      newList.Add(j) 
     newList2.Add(newList) 
+0

什麼是錯誤的輸出,給它看起來不像你想要的? – jwilner

回答

0

內環很容易被寫成一個列表理解:

[ j.Mirror(mirPlane) for j in i ] 

等都可以外環:

[ <inner part here> for i in otherElem ] 

將其組合在一起,我們得到了一個嵌套列表理解:

newList2 = [ 
    [ j.Mirror(mirPlane) for j in i ] 
    for i in otherElem 
] 
+0

我不是程序員,但是這個解決方案看起來非常好(也可以工作)。 Tnx –

1

它可以用嵌套列表理解來完成,像這樣。

otherElem=[[1, 2, 3, 4],[5, 6, 7, 8], [9, 10, 11, 12]] 

l = [[an_elem * 2 for an_elem in inner_list] for inner_list in otherElem] 

print l 

結果是,

[[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]] 

在這裏,每一個元素上的操作是乘以2,你的情況是j.Mirror(mirPlane),這我不知道,它返回什麼。

1

其他答案是正確的;列表理解可能是在Python中執行此操作的最佳方式。同時,您列出的解決方案具體看起來有什麼問題,即每次查看內部列表時都需要創建一個新列表。它應該看起來像:

new_list_of_lists = [] 
for old_list in old_list_of_lists: 
    new_list = [] 
    new_list_of_lists.append(new_list) 
    for old_item in old_list: 
     new_item = transformation(old_item) 
     new_list.append(new_item) 

這七線是完全等同於更短的嵌套列表理解,所以你可以看到,爲什麼這些內涵是最好!

+0

Tnx,就像那個老派的方法:) –

1

您可以使用operator來調用一個很好的嵌套調用。

import operator 

upper = operator.methodcaller('upper') 
list =[['a', 'b', 'c', 'd'],['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']] 
print [map(upper, sub_list) for sub_list in list] 
# [['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L']]