通过将两个长度不均匀的列表压缩在一起来创建字典 [英] Create a dictionary by zipping together two lists of uneven length

查看:26
本文介绍了通过将两个长度不均匀的列表压缩在一起来创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同长度的列表,L1 和 L2.L1 比 L2 长.我想得到一个字典,其中 L1 的成员作为键,L2 的成员作为值.

I have two lists different lengths, L1 and L2. L1 is longer than L2. I would like to get a dictionary with members of L1 as keys and members of L2 as values.

一旦L2的所有成员都用完.我想从头开始,从 L2[0] 开始.

As soon as all the members of L2 are used up. I would like to start over and begin again with L2[0].

L1 = ['A', 'B', 'C', 'D', 'E']    
L2 = ['1', '2', '3']    
D = dict(zip(L1, L2))    
print(D)

正如预期的那样,输出是这样的:

As expected, the output is this:

{'A': '1', 'B': '2', 'C': '3'}

我想实现的目标如下:

{'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}

推荐答案

使用 itertools.cycle 循环到L2的开头:

from itertools import cycle
dict(zip(L1, cycle(L2)))
# {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}

<小时>

在您的情况下,将 L2 与其自身连接也有效.


In your case, concatenating L2 with itself also works.

# dict(zip(L1, L2 * 2))
dict(zip(L1, L2 + L2))
# {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}

这篇关于通过将两个长度不均匀的列表压缩在一起来创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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