不知道如何查找,但是从itertools
函数izip_longest可以做到这一点:izip_longest('ABCD', 'xy', fillvalue='-')
-> Ax By C- D-
我希望一个可迭代的库可以执行以下操作:izip_longest_better('ABCDE', 'xy')
-> Ax By Cx Dy Ex
优选地,对于任意数量的可迭代,用于生成数百万个组合。我会自己写,但是我想问一下,因为我确定我自己不会很pythonic。
太棒了,这是我没有尝试过的循环。我还可以通过嵌套数组而不是迭代器的循环来使工作正常,但这要好得多。我最终使用的是类似izip的处理方式”
编辑:
最终以
def izip_longest_repeat(* args):
如果参数:
列表=已排序(args,键= len,反向= True)
结果= list(itertools.izip(*([[lists [0]] + [itertools.cycle(l)for list [1:]]中的l))))
别的:
结果= [()]
返回结果
最佳答案
像这样吗?
>>> import itertools
>>>
>>> a = 'ABCDE'
>>> b = 'xy'
>>>
>>> list(itertools.izip_longest(a, b, fillvalue='-'))
[('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-'), ('E', '-')]
>>> list(itertools.izip(a, itertools.cycle(b)))
[('A', 'x'), ('B', 'y'), ('C', 'x'), ('D', 'y'), ('E', 'x')]
等。还有一个任意数量的iterables变体(假设您不希望第一个参数循环,并且您对itertools.product并不真正感兴趣):
>>> a = 'ABCDE'
>>> bs = ['xy', (1,2,3), ['apple']]
>>> it = itertools.izip(*([a] + [itertools.cycle(b) for b in bs]))
>>> list(it)
[('A', 'x', 1, 'apple'), ('B', 'y', 2, 'apple'), ('C', 'x', 3, 'apple'),
('D', 'y', 1, 'apple'), ('E', 'x', 2, 'apple')]
关于python - izip_longest与循环而不是fillvalue,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9542358/