【问题标题】:izip_longest with looping instead of fillvalueizip_longest 使用循环而不是填充值
【发布时间】:2012-03-21 11:47:14
【问题描述】:

不知道如何四处寻找,但从 itertools 函数 izip_longest 可以做到这一点:

izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-

我希望一个可迭代的库能够做到这一点:

izip_longest_better('ABCDE', 'xy') --> Ax By Cx Dy Ex

最好用于任意数量的可迭代对象,用于生成数百万个组合。我会自己写,但我想我会问,因为我确信我自己的不会很 Python。

太棒了,这是我没有尝试过的循环。我还能够通过在数组而不是迭代器上嵌套 for 循环来获得一些工作,但这要好得多。我最后用的是这个处理类似于 izip"

编辑: 结束了

def izip_longest_repeat(*args):
    如果参数:
        列表 = 排序(参数,键 = len,反向 = 真)
        结果 = list(itertools.izip(*([lists[0]] + [itertools.cycle(l) for l in lists[1:]])))
    别的:
        结果 = [()]
    返回结果

【问题讨论】:

    标签: python


    【解决方案1】:

    这样的?

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

    【讨论】:

    • 太棒了,这是我没有尝试过的循环。我还能够通过在数组而不是迭代器上嵌套 for 循环来获得一些工作,但这要好得多。我最终使用的是类似于 izip 的处理方式。 lists = sorted(args, key=len, reverse=True)result = list(itertools.izip(*([lists[0]] + [itertools.cycle(l) for l in lists[1:]])))
    • 在从列表中生成字典时非常重要,该列表在前一些元素中有标题!
    【解决方案2】:

    对于 Python 3,您想使用 zip_longest 由于 izip_longest 已被弃用。

    import itertools
    list = list(itertools.zip_longest('ABCD', 'xy', fillvalue='-'))
    print(list) // --> Ax By C- D-
    

    【讨论】:

      猜你喜欢
      • 2022-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多