Python:像这样合并列表

时间:2015-08-29 09:31:58

标签: python list merge

在保持整体结构的同时,合并两个简单的嵌套列表有很多麻烦。例如:

# 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

1 个答案:

答案 0 :(得分: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']]