gpt4 book ai didi

python - izip_longest 循环而不是填充值

转载 作者:太空狗 更新时间:2023-10-29 22:08:20 27 4
gpt4 key购买 nike

不确定如何四处寻找这个,但是从 itertools 函数 izip_longest这样做:

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

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

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

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

太棒了,这是我没有尝试过的循环。我还能够通过在数组而不是迭代器上嵌套 for 循环来使某些东西工作,但这要好得多。我最后用的是这个类似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

最佳答案

是这样的吗?

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

关于python - izip_longest 循环而不是填充值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9542358/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com