合并清单清单 [英] Merging lists of lists

查看:67
本文介绍了合并清单清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,每个列表具有相等数量的项目.这两个列表如下所示:

I have two lists of lists that have equivalent numbers of items. The two lists look like this:

L1 = [[1, 2], [3, 4], [5, 6, 7]]

L2 =[[a, b], [c, d], [e, f, g]]

我正在寻找一个看起来像这样的列表:

I am looking to create one list that looks like this:

Lmerge = [[[a, 1], [b,2]], [[c,3], [d,4]], [[e,5], [f,6], [g,7]]]

我正在尝试使用map():

map(list.__add__, L1, L2),但输出生成一个平面列表.

map(list.__add__, L1, L2) but the output produces a flat list.

合并两个列表列表的最佳方法是什么?预先感谢.

What is the best way to combine two lists of lists? Thanks in advance.

推荐答案

您可以zip列表,然后再次zip生成的元组...

You can zip the lists and then zip the resulting tuples again...

>>> L1 = [[1, 2], [3, 4], [5, 6, 7]]
>>> L2 =[['a', 'b'], ['c', 'd'], ['e', 'f', 'g']]
>>> [list(zip(a,b)) for a,b in zip(L2, L1)]
[[('a', 1), ('b', 2)], [('c', 3), ('d', 4)], [('e', 5), ('f', 6), ('g', 7)]]

如果您需要从头到尾列出清单,请与`map相结合:

If you need lists all the way down, combine with `map:

>>> [list(map(list, zip(a,b))) for a,b in zip(L2, L1)]
[[['a', 1], ['b', 2]], [['c', 3], ['d', 4]], [['e', 5], ['f', 6], ['g', 7]]]

这篇关于合并清单清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆