如何压缩两个不同大小的列表? [英] How to zip two differently sized lists?

查看:84
本文介绍了如何压缩两个不同大小的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to zip two list with different length

例如

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

我希望如此

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

但是内置的zip不会重复与更大尺寸的列表配对. 是否存在任何内置方法可以实现此目的? 谢谢

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

这是我的代码

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

推荐答案

您可以使用 :

制作一个迭代器,从迭代器返回元素,并保存每个元素的副本.当Iterable耗尽时,从保存的副本中返回元素.无限重复.

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.

示例:

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)

这篇关于如何压缩两个不同大小的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆