如何压缩嵌套列表的每个元素?

时间:2019-11-06 15:12:23

标签: python

我有两个嵌套列表:

l = [
    ['a', 'b', 'c'], 
    ['d', 'e', 'f']
    ]

l2 = [
     ['a', 'b', 'c'], 
     ['d', 'e', 'f']
     ]

我想将两个嵌套列表的每个元素合并成一个新的单独列表,如下所示:

nl = [
     ['a', 'a'], ['b', 'b'], ['c', 'c'], 
     ['d', 'd'], ['e','e'], ['f','f']
     ]

但是我的代码:

r = []
r+= [[j + ' , '+ k] for j,k in zip(l[i],l2[i])]

只需给我嵌套列表中的最后一个列表作为结果即可

nl = [['f','f']]

如何更改代码以将所有内容都放入nl的两个嵌套列表中?

1 个答案:

答案 0 :(得分:2)

from itertools import chain

l = [
  ['a', 'b', 'c'], 
  ['d', 'e', 'f']
]

l2 = [
  ['a', 'b', 'c'], 
  ['d', 'e', 'f']
]

nl = list(map(list, zip(chain(*l), chain(*l2))))

输出:

[
  ['a', 'a'],
  ['b', 'b'],
  ['c', 'c'],
  ['d', 'd'],
  ['e', 'e'],
  ['f', 'f']
]