2015-08-29 59 views
0

我有很多麻煩來合併兩個簡單的嵌套列表,同時保持整體結構。例如:Python:像這樣合併列表

# From this source: 

x = [['a','b','c'],['d','e','f'],['g','h','i']] 
y = [['A','B','C'],['D','E','F'],['G','H','I']] 


# To this result: 

z = [[['a','A'],['b','B'],['c','C']], 
    [['d','D'],['e','E'],['f','F']], 
    [['g','G'],['h','H'],['i','I']]] 

有什麼想法嗎?


這裏,一些(尷尬)的代碼,我嘗試:

X = [] 
Y = [] 

for i in iter(x[:]): 
    X.append('=') 
    for v in iter(i[:]): 
     X.append(v) 
print X; print 

for i in iter(y[:]): 
    Y.append('=') 
    for v in iter(i[:]): 
     Y.append(v) 
print Y; print 


for i in zip(X, Y): 
    print i 
+0

@AnttiHaapala無需進行任何嘗試。有人會盡快發佈工作解決方案。 – juanchopanza

+0

@juanchopanza所以看起來。 –

+0

@AnttiHaapala這絕對是一個「寫我的代碼」網站。 – juanchopanza

回答

3
print([list(map(list,zip(*t))) for t in zip(x,y)]) 
[[['a', 'A'], ['b', 'B'], ['c', 'C']], 
[['d', 'D'], ['e', 'E'], ['f', 'F']], 
[['g', 'G'], ['h', 'H'], ['i', 'I']]] 

步驟:

In [20]: zip(x,y) # zip the lists together 
Out[20]: 
[(['a', 'b', 'c'], ['A', 'B', 'C']), 
(['d', 'e', 'f'], ['D', 'E', 'F']), 
(['g', 'h', 'i'], ['G', 'H', 'I'])] 

In [21]: t = (['a', 'b', 'c'], ['A', 'B', 'C']) # first "t" 
In [22]: zip(*t) # transpose, row to columns, columns to rows 
Out[22]: [('a', 'A'), ('b', 'B'), ('c', 'C')] 

In [23]: list(map(list,zip(*t))) # convert inner tuples to lists 
Out[23]: [['a', 'A'], ['b', 'B'], ['c', 'C']] 
+1

是啊!太讚了。 –