Python 如何压缩两个不同大小的列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19686533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:22:17  来源:igfitidea点击:

How to zip two differently sized lists?

pythonlistpython-3.x

提问by user2131116

I want to zip two list with different length

我想压缩两个不同长度的列表

for example

例如

A = [1,2,3,4,5,6,7,8,9]
B = ["A","B","C"]

and I expect this

我期待这个

[(1, 'A'), (2, 'B'), (3, 'C'), (4, 'A'), (5, 'B'), (6, 'C'), (7, 'A'), (8, 'B'), (9, 'C')]

But the build-in zipwon't repeat to pair with the list with larger size . Does there exist any build-in way can achieve this? thanks

但是内置zip不会重复与更大 size 的列表配对。是否存在任何内置方式可以实现这一目标?谢谢

here is my code

这是我的代码

idx = 0
zip_list = []
for value in larger:
    zip_list.append((value,smaller[idx]))
    idx += 1
    if idx == len(smaller):
        idx = 0

采纳答案by sloth

You can use itertools.cycle:

您可以使用itertools.cycle

Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely.

使迭代器从可迭代对象返回元素并保存每个元素的副本。当迭代用完时,从保存的副本中返回元素。无限重复。

Example:

例子:

A = [1,2,3,4,5,6,7,8,9]
B = ["A","B","C"]

from itertools import cycle
zip_list = zip(A, cycle(B)) if len(A) > len(B) else zip(cycle(A), B)

回答by Eser Aygün

Try this.

尝试这个。

A = [1,2,3,4,5,6,7,8,9]
B = ["A","B","C"]
Z = []
for i, a in enumerate(A):
    Z.append((a, B[i % len(B)]))

Just make sure that the larger list is in A.

只需确保较大的列表在A.

回答by James Robinson

There is probably a better way, but you could make a function that repeats your list to whatever length you want.

可能有更好的方法,但您可以制作一个函数,将您的列表重复到您想要的任何长度。

def repeatlist(l,i):
    '''give a list and a total length'''
    while len(l) < i:
        l += l
    while len(l) > i:
        l.pop()

Then do

然后做

repeatlist(B,len(A))
zip_list = zip(A,B)

回答by f5r5e5d

symmetric, no conditionals one liner

对称,无条件单行

[*zip(A*(len(B)//len(A) + 1), B*(len(A)//len(B) + 1))]

which strictly answers 'How to zip two differentlysized lists?'

严格回答“如何压缩两个不同大小的列表?”

needs a patch for equal sized lists to be general:

需要一个相同大小列表的补丁才能通用:

[*(zip(A, B) if len(A) == len(B)
         else zip(A*(len(B)//len(A) + 1),
                  B*(len(A)//len(B) + 1)))]

回答by dimitris_ps

And nowadays with list comprehentions

现在有了列表理解

[(i, B[i % 3 - 1]) for i in A]

Or if the elements of Aare not sequential and not worrying about list lengths

或者如果 的元素A不是顺序的并且不担心列表长度

[(j, B[i % len(B)]) for i, j in enumerate(A)] if len(A) >= len(B) else \
[(A[i % len(A)], j) for i, j in enumerate(B)]

回答by Solomon Ucko

For a version that works with any finite number of potentially infinite iterables in any order:

对于以任何顺序处理任何有限数量的潜在无限迭代的版本:

from itertools import cycle, tee, zip_longest

def cyclical_zip(*iterables):
    iterables_1, iterables_2 = zip(*map(tee, iterables))  # Allow proper iteration of iterators

    for _, x in zip(
            zip_longest(*iterables_1),      # Limit             by the length of the longest iterable
            zip(*map(cycle, iterables_2))): #       the cycling
        yield x

assert list(cyclical_zip([1, 2, 3], 'abcd', 'xy')) == [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'x'), (1, 'd', 'y')]  # An example and test case

回答by Dane White

Solution for an arbitrary number of iterables, and you don't know which one is longest (also allowing a default for any empty iterables):

任意数量的迭代的解决方案,你不知道哪个最长(也允许任何空迭代的默认值):

from itertools import cycle, zip_longest

def zip_cycle(*iterables, empty_default=None):
    cycles = [cycle(i) for i in iterables]
    for _ in zip_longest(*iterables):
        yield tuple(next(i, empty_default) for i in cycles)

for i in zip_cycle(range(2), range(5), ['a', 'b', 'c'], []):
    print(i)

Outputs:

输出:

(0, 0, 'a', None)
(1, 1, 'b', None)
(0, 2, 'c', None)
(1, 3, 'a', None)
(0, 4, 'b', None)

回答by Gajendra D Ambi

d1=['one','two','three']
d2=[1,2,3,4,5]

Zip

压缩

zip(d1,d2)
<zip object at 0x05E494B8>

list of zip

邮编清单

list(zip(d1,d2))

dictionary of list of zip

zip 目录字典

{'one': 1, 'two': 2, 'three': 3}

Note: Python 3.7+

注意:Python 3.7+