网站建设和网站优化的区别,网页主题参考,网址模版,中企动力员工感受将两个或多个列表合并为一个列表#xff0c;并根据每个输入列表中的元素的位置将其组合在一起。
这个需求在实际开发过程中应该说非常常见#xff0c;当然python也给我们内置了相关方法#xff01;
zip(*iterables, strictFalse)
在多个迭代器上并行迭代#xff0c;从每…将两个或多个列表合并为一个列表并根据每个输入列表中的元素的位置将其组合在一起。
这个需求在实际开发过程中应该说非常常见当然python也给我们内置了相关方法
zip(*iterables, strictFalse)
在多个迭代器上并行迭代从每个迭代器返回一个数据项组成元组。 [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], strictTrue):
... print(item)
(0, fee)
(1, fi)
(2, fo)
Traceback (most recent call last):File stdin, line 1, in module
ValueError: zip() argument 2 is longer than argument 1
如果未指定 strictTrue 参数所有导致可迭代对象长度不同的错误都会被抑制这可能会在程序的其他地方表现为难以发现的错误。
为了让所有的可迭代对象具有相同的长度长度较短的可用常量进行填充。python内置模块itertools中的zip_longest()函数来完成。
itertools.zip_longest(**iterables , fillvalueNone) list(itertools.zip_longest(range(3), [fee, fi, fo, fum]))
[(0, fee), (1, fi), (2, fo), (None, fum)]
其源码如下
def zip_longest(*args, fillvalueNone):# zip_longest(ABCD, xy, fillvalue-) -- Ax By C- D-iterators [iter(it) for it in args]num_active len(iterators)if not num_active:returnwhile True:values []for i, it in enumerate(iterators):try:value next(it)except StopIteration:num_active - 1if not num_active:returniterators[i] repeat(fillvalue)value fillvaluevalues.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列表中返回。