Python 是否有一个类似拉链的功能,可以垫到最长的长度?
是否有一个内置函数可以像这样工作,但它将填充结果,以便结果列表的长度是最长输入的长度,而不是最短输入的长度Python 是否有一个类似拉链的功能,可以垫到最长的长度?,python,list,zip,Python,List,Zip,是否有一个内置函数可以像这样工作,但它将填充结果,以便结果列表的长度是最长输入的长度,而不是最短输入的长度 对于Python2.6x,使用itertools模块 对于Python 3,请改用(无前导i) 在Python3中,您可以使用 通过使用fillvalue参数,可以使用与None不同的值进行填充: >>> list(itertools.zip_longest(a, b, c, fillvalue='foo')) [('a1', 'b1', 'c1'), ('foo', '
对于Python2.6x,使用
itertools
模块
对于Python 3,请改用(无前导i
)
在Python3中,您可以使用
通过使用fillvalue
参数,可以使用与None
不同的值进行填充:
>>> list(itertools.zip_longest(a, b, c, fillvalue='foo'))
[('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]
使用Python2,您可以使用(Python2.6+),也可以使用map
和None
。它鲜为人知(但是在Python3.x中,map
发生了变化,所以这只适用于Python2.x)
非itertools Python 3解决方案:
def zip_longest(*lists):
def g(l):
for item in l:
yield item
while True:
yield None
gens = [g(l) for l in lists]
for _ in range(max(map(len, lists))):
yield tuple(next(g) for g in gens)
if len(list1) < len(list2):
list1.extend([None] * (len(list2) - len(list1)))
else:
list2.extend([None] * (len(list1) - len(list2)))
非itertools My Python 2解决方案:
def zip_longest(*lists):
def g(l):
for item in l:
yield item
while True:
yield None
gens = [g(l) for l in lists]
for _ in range(max(map(len, lists))):
yield tuple(next(g) for g in gens)
if len(list1) < len(list2):
list1.extend([None] * (len(list2) - len(list1)))
else:
list2.extend([None] * (len(list1) - len(list2)))
如果len(列表1)
Im使用2d数组,但概念与使用python 2.x类似:
if len(set([len(p) for p in printer])) > 1:
printer = [column+['']*(max([len(p) for p in printer])-len(column)) for column in printer]
我们没有非itertools Python 3解决方案吗?@PascalvKooten它不是必需的
itertools
是一个内置的C模块。如果您想使代码与python 2和python 3兼容,可以使用six.moves.zip\u longest
。请添加此代码工作原理的解释。或者为什么这是正确的答案
if len(list1) < len(list2):
list1.extend([None] * (len(list2) - len(list1)))
else:
list2.extend([None] * (len(list1) - len(list2)))
if len(set([len(p) for p in printer])) > 1:
printer = [column+['']*(max([len(p) for p in printer])-len(column)) for column in printer]