如何将两个列表合并为多个列表的列表? [英] How to merge two lists into a list of multiple lists?
问题描述
给出两个列表lst1和lst2:
Given two lists lst1 and lst2:
lst1 = ['a']
lst2 = [['b'],
['b', 'c'],
['b', 'c', 'd']]
我想将它们合并为具有所需输出的多个列表的列表,如下所示:
I'd like to merge them into a list of multiple lists with a desired output like this:
desiredList = [['a', ['b']],
['a', ['b', 'c']],
['a', ['b', 'c', 'd']]]
这是我使用 lst1 + lst2
和 list.append()
进行的尝试之一:
Here is one of my attempts that comes close using lst1 + lst2
and list.append()
:
lst3 = []
for elem in lst2:
new1 = lst1
new2 = elem
theNew = new1 + new2
lst3.append(theNew)
print(lst3)
#Output:
#[['a', 'b'],
#['a', 'b', 'c'],
#['a', 'b', 'c', 'd']]
对此进行扩展,我认为 theNew = new1.append(new2)
的另一个变体可以解决问题.但是没有:
Expanding on this, I thought another variation with theNew = new1.append(new2)
would do the trick. But no:
lst3 = []
for elem in lst2:
new1 = lst1
new2 = elem
#print(new1 + new2)
#theNew = new1 + new2
theNew = new1.append(new2)
lst3.append(theNew)
print(lst3)
# Output:
[None, None, None]
通过 extend
,您将获得相同的结果.
And you'll get the same result with extend
.
我想这应该很容易,但是我很茫然.
I guess this should be really easy, but I'm at a loss.
谢谢您的任何建议!
推荐答案
您可以使用带有 fillvalue
的 itertools.zip_longest
实现所需的输出:
You could achieve your desired output with itertools.zip_longest
with a fillvalue
:
>>> from itertools import zip_longest
>>> list(zip_longest(lst1, lst2, fillvalue=lst1[0]))
[('a', ['b']), ('a', ['b', 'c']), ('a', ['b', 'c', 'd'])]
或者如果您需要列表列表:
Or if you need a list of lists:
>>> [list(item) for item in zip_longest(lst1, lst2, fillvalue=lst1[0])]
[['a', ['b']], ['a', ['b', 'c']], ['a', ['b', 'c', 'd']]]
请注意,这假设 lst1
始终包含单个元素,如您的示例一样.
Note this assumes that lst1
always contains a single element as in your example.
这篇关于如何将两个列表合并为多个列表的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!