0

为简单起见进行了编辑,因为我已将问题指向“参数拆包”。
我正在尝试编写一个将任意数量的列表作为参数交错的函数。所有列表的长度相同。该函数应返回一个列表,其中包含交错的输入列表中的所有元素。

def interleave(*args):

    for i, j, k in zip(*args):
        print(f"On {i} it was {j} and the temperature was {k} degrees celsius.")

interleave(["Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split()],["rainy rainy sunny cloudy rainy sunny sunny".split()],[10,12,12,9,9,11,11])

输出:

On ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] it was ['rainy', 'rainy', 'sunny', 'cloudy', 'rainy', 'sunny', 'sunny'] and the temperature was 10 degrees celsius.

所需的输出:

On Monday it was rainy and the temperature was 10 degrees celsius.
On Tuesday it was rainy and the temperature was 12 degrees celsius.
On Wednesday it was sunny and the temperature was 12 degrees celsius.
On Thursday it was cloudy and the temperature was 9 degrees celsius.
On Friday it was rainy and the temperature was 9 degrees celsius.
On Saturday it was sunny and the temperature was 11 degrees celsius.
On Sunday it was sunny and the temperature was 11 degrees celsius.
4

2 回答 2

1

不要将结果包装split在列表中。所以,改变

interleave(["Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split()],["rainy rainy sunny cloudy rainy sunny sunny".split()],[10,12,12,9,9,11,11])

interleave("Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(),"rainy rainy sunny cloudy rainy sunny sunny".split(),[10,12,12,9,9,11,11]).

前者将产生两个长度为 1 的列表和一个长度为 7 的列表作为 的参数interleave,而后者/更改将产生三个长度为 7 的列表作为参数。后者是zip操作员按照您的意愿工作所需要的。

于 2020-01-18T18:16:53.823 回答
1

文档的配方部分itertools称之为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))

对于(相等大小的)列表,您可以将其简化为

def interleave(*args):
    return list(chain.from_iterable(zip(*args)))
于 2020-01-18T14:51:54.587 回答