且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

合并不同长度的python列表

更新时间:2023-12-05 16:37:04

一种选择是使用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.