Python将两个或多个列表合并为一个列表,并根据每个输入列表中的元素的位置将其组合在一起

将两个或多个列表合并为一个列表,并根据每个输入列表中的元素的位置将其组合在一起。

这个需求在实际开发过程中应该说非常常见,当然python也给我们内置了相关方法!

zip(*iterables, strict=False)

在多个迭代器上并行迭代,从每个迭代器返回一个数据项组成元组。

>>> [item for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice'])]
[(1, 'sugar'), (2, 'spice'), (3, 'everything nice')]

如果合并的多个列表长度不一致,则默认迭代完最短的一个停止,即strict参数为False!

>>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum']))                           
[(0, 'fee'), (1, 'fi'), (2, 'fo')]

因此上,如果你确定你要迭代的列表长度一致,则建议将strict设置为True,如果一个可迭代对象在其他几个之前被耗尽则会引发 ValueError

>>> for item in zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True):
...     print(item)
(0, 'fee')
(1, 'fi')
(2, 'fo')
Traceback (most recent call last):
  File "", line 1, in 
ValueError: zip() argument 2 is longer than argument 1

如果未指定 strict=True 参数,所有导致可迭代对象长度不同的错误都会被抑制,这可能会在程序的其他地方表现为难以发现的错误。

为了让所有的可迭代对象具有相同的长度,长度较短的可用常量进行填充。python内置模块itertools中的zip_longest()函数来完成。

itertools.zip_longest(**iterables ,  fillvalue=None)​​​​​​​

>>> list(itertools.zip_longest(range(3), ['fee', 'fi', 'fo', 'fum']))
[(0, 'fee'), (1, 'fi'), (2, 'fo'), (None, 'fum')]

​​​​​​​其源码如下:​​​​​​​

def zip_longest(*args, fillvalue=None):
    # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
    iterators = [iter(it) for it in args]
    num_active = len(iterators)
    if not num_active:
        return
    while True:
        values = []
        for i, it in enumerate(iterators):
            try:
                value = next(it)
            except StopIteration:
                num_active -= 1
                if not num_active:
                    return
                iterators[i] = repeat(fillvalue)
                value = fillvalue
            values.append(value)
        yield tuple(values)

当然,我们自己也可以手动去实现这样的需求!​​​​​​​​​​​​​​

def merge(*args, fill_value = None):
    """
    合并多个列表成一个二维列表。

    Args:
        *args: 任意数量的列表参数。
        fill_value: 填充值,默认为None。

    Returns:
        list: 合并后的二维列表。
    """
    max_length = max([len(lst) for lst in args])
    result = []
    for i in range(max_length):
        result.append([
            args[k][i] if i < len(args[k]) else fill_value for k in range(len(args))
        ])
    return result
print(merge([1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]))print(merge([1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12, 13], fill_value = 0))
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]][[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12], [0, 0, 0, 13]]

这个函数的功能是找到列表中每列的最长长度,并将每列按照该长度进行填充。函数首先使用列表推导式找到所有列表的最长长度,然后使用嵌套的for循环遍历每一列,将每列填充为最长长度的值或者使用指定的填充值。最后将填充后的结果存储在result列表中返回。

你可能感兴趣的:(python,python,开发语言,前端)