【问题标题】:Unpack *args for use in a for loop解压 *args 以在 for 循环中使用
【发布时间】:2018-06-18 18:12:36
【问题描述】:

这是我的出发点。这按原样工作。

l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]
l3 = [9, 10, 11, 12]


def interleave(iterable1, iterable2):
    for item1, item2 in zip(iterable1, iterable2):
        yield item1
        yield item2


print(interleave(l1, l2))
print('-' * 30)
print(list(interleave(l1, l2)))

如果我想扩展它以使用所有三个列表,我可以这样做:

l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]
l3 = [9, 10, 11, 12]


def interleave(*args):
    for item1, item2, item3 in zip(*args):
        yield item1
        yield item2
        yield item3


print(interleave(l1, l2, l3))
print('-' * 30)
print(list(interleave(l1, l2, l3)))

但是,我使用“解决”了接收任意数量的输入迭代的问题 *args,但我的项目分配仍然是手动的。

我想能够说:

def interleave(*args):
    for *items in zip(*args):
        yield items

为了让我可以将任意数量的输入变量解压缩到 *items 中,但我得到了这个错误: SyntaxError: starred assignment target must be in a list or tuple

我不想说*items = <something>。我想让 *items 接收任意数量的输入变量。

如果我有六个列表,我不想说 item1、item2、...、item6,然后是相同数量的产量。

这真的不是很可扩展。

有没有办法做我所追求的?

【问题讨论】:

  • 就是这样。 '屈服于'。是时候查一下了。
  • 你可以用from itertools import chain; chain.from_iterable(zip(*args))你知道的。

标签: python python-3.x arguments python-3.6


【解决方案1】:

对于 3.3 之前的 Python,请使用嵌套的 for 循环。

def interleave(*args):
    for items in zip(*args):
        for item in items:
            yield item

对于 Python 3.3+,您可以将 yield from 用于 generator delegation,这是上述语法糖。

def interleave(*args):
    for items in zip(*args):
        yield from items

或者最后,如果您需要一个允许不同长度列表的更通用的解决方案,请使用itertools recipes 中的roundrobin 函数。

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    num_active = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while num_active:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            # Remove the iterator we just exhausted from the cycle.
            num_active -= 1
            nexts = cycle(islice(nexts, num_active))

【讨论】:

    【解决方案2】:

    嵌套循环?

    def interleave(*args):
        for items in zip(*args): 
            for item in items:
                yield items
    

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      • 2012-09-30
      相关资源
      最近更新 更多