合并不同长度的python列表 [英] Merge python lists of different lengths
问题描述
我正在尝试合并两个python列表,其中它们在给定索引处的值将在新列表中形成一个列表(元素).例如:
I am attempting to merge two python lists, where their values at a given index will form a list (element) in a new list. For example:
merge_lists([1,2,3,4], [1,5]) = [[1,1], [2,5], [3], [4]]
我可以迭代此函数以组合更多列表.最有效的方法是什么?
I could iterate on this function to combine ever more lists. What is the most efficient way to accomplish this?
在测试了我之前选择的答案后,我意识到我还有其他标准和更普遍的问题.我还想合并包含列表 或 值的列表.例如:
Upon testing the answer I had previously selected, I realized I had additional criteria and a more general problem. I would also like to combine lists containing lists or values. For example:
merge_lists([[1,2],[1]] , [3,4]) = [[1,2,3], [1,4]]
在这种情况下,当前提供的答案会生成更高维度的列表.
The answers currently provided generate lists of higher dimensions in cases like this.
推荐答案
一种选择是使用itertools.zip_longest
(在python 3中):
One option is to use itertools.zip_longest
(in python 3):
from itertools import zip_longest
[[x for x in t if x is not None] for t in zip_longest([1,2,3,4], [1,5])]
# [[1, 1], [2, 5], [3], [4]]
如果您喜欢设置:
[{x for x in t if x is not None} for t in zip_longest([1,2,3,4], [1,5])]
# [{1}, {2, 5}, {3}, {4}]
在python 2中,使用itertools.izip_longest
:
from itertools import izip_longest
[[x for x in t if x is not None] for t in izip_longest([1,2,3,4], [1,5])]
#[[1, 1], [2, 5], [3], [4]]
更新处理稍微复杂一点的情况:
Update to handle the slightly more complicated case:
def flatten(lst):
result = []
for s in lst:
if isinstance(s, list):
result.extend(s)
else:
result.append(s)
return result
这可以很好地处理以上两种情况:
This handles the above two cases pretty well:
[flatten(x for x in t if x is not None) for t in izip_longest([1,2,3,4], [1,5])]
# [[1, 1], [2, 5], [3], [4]]
[flatten(x for x in t if x is not None) for t in izip_longest([[1,2],[1]] , [3,4])]
# [[1, 2, 3], [1, 4]]
请注意,即使此方法适用于以上两种情况,但由于情况会变得非常复杂,因此它仍然可以在更深层的嵌套结构下分解.有关更一般的解决方案,请参见此处.
Note even though this works for the above two cases, but it can still break under deeper nested structure, since the case can get complicated very quickly. For a more general solution, you can see here.
这篇关于合并不同长度的python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!