izip_longest循环而不是fillvalue

时间:2012-03-03 00:48:57

标签: python

不确定如何查看此内容,但是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):
    if args:
        lists = sorted(args, key=len, reverse=True)
        result = list(itertools.izip(*([lists[0]] + [itertools.cycle(l) for l in lists[1:]])))
    else:
        result = [()]
    return result

2 个答案:

答案 0 :(得分:14)

这样的东西?

>>> 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')]

等。并且存在任意数量的可迭代变体(假设您不希望第一个参数循环,并且您对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')]

答案 1 :(得分:1)

对于Python 3,您想使用enter image description here 由于objIE.Document.getElementsByClassName("form-control")(1).Value = Sheets("Sheet1").Range("A1").Value 'click the 'go' button objIE.Document.getElementsByClassName("btn search-btn")(0).Click 已被弃用。

izip_longest