Python 在不相等的列表上使用zip_,但重复最后一个条目,而不是返回“无”
有一个关于此的现有线程 但我追求的不完全是。 我需要它复制列表上的前一个条目,而不是返回None 这可能吗Python 在不相等的列表上使用zip_,但重复最后一个条目,而不是返回“无”,python,list,python-2.7,itertools,Python,List,Python 2.7,Itertools,有一个关于此的现有线程 但我追求的不完全是。 我需要它复制列表上的前一个条目,而不是返回None 这可能吗 a = ["bottle","water","sky"] b = ["red", "blue"] for i in itertools.izip_longest(a,b): print i #result # ('bottle', 'red') # ('water', 'blue
a = ["bottle","water","sky"]
b = ["red", "blue"]
for i in itertools.izip_longest(a,b):
print i
#result
# ('bottle', 'red')
# ('water', 'blue')
# ('sky', None)
# What I want on the third line is
# ('sky', 'blue')
您可以在较短的列表中添加其最后一个值的值。然后使用正则表达式,结果将是较长列表的长度:
from itertools import izip, repeat, chain
def izip_longest_repeating(seq1, seq2):
if len(seq1) < len(seq2):
repeating = seq1[-1]
seq1 = chain(seq1, repeat(repeating))
else:
repeating = seq2[-1]
seq2 = chain(seq2, repeat(repeating))
return izip(seq1, seq2)
print(list(izip_longest_repeating(a, b)))
# [('bottle', 'red'), ('water', 'blue'), ('sky', 'blue')]
itertools.izip_longest接受一个可选的fillvalue参数,该参数提供在较短列表用尽后使用的值。fillvalue默认为None,给出问题中显示的行为,但您可以指定不同的值以获得所需的行为:
如果lenafrom itertools import izip as zip # Python2 only
def zip_longest_repeating(*iterables):
iters = [iter(i) for i in iterables]
sentinel = object()
vals = tuple(next(it, sentinel) for it in iters)
if any(val is sentinel for val in vals):
return
yield vals
while True:
cache = vals
vals = tuple(next(it, sentinel) for it in iters)
if all(val is sentinel for val in vals):
return
vals = tuple(old if new is sentinel else new for old, new in zip(cache, vals))
yield vals
list(zip_longest_repeating(['a'], ['b', 'c'], ['d', 'r', 'f']))
# [('a', 'b', 'd'), ('a', 'c', 'r'), ('a', 'c', 'f')]