解包*args以便在for循环中使用

2024-03-28 14:47:21 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的出发点。这是正常的。你知道吗

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

允许我将任意数量的输入变量解包到*项中,但出现以下错误: SyntaxError: starred assignment target must be in a list or tuple

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

如果我有六个列表,我不想说item1,item2,…,item6,后跟相同数量的收益。你知道吗

这真的不是很好扩展。你知道吗

有什么办法可以做我想做的事吗?你知道吗


Tags: inl1fordefargsitemsziplist
2条回答

嵌套循环?你知道吗

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

对于3.3之前的Python,请使用嵌套For循环。你知道吗

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

对于python3.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))

相关问题 更多 >