[英]merge 2 different lists to dictionary
I am trying to merge two lists with different lengths to dictionary. 我正在尝试将两个不同长度的列表合并到字典中。 Pls help
请帮助
listA = ['2','4','6','8','10','12','14','16','18','20','22','24','26','28']
listB = ['host1','host2','host3','host4']
expected output: 预期输出:
{
host1: [2,10,18,26],
host2: [4,12,20,28],
host3: [6,14,22],
host4 : [8,16,24]
}
It looks like you want to have a dictionary where every fourth element in listA
is a member of listB
. 它看起来像你想拥有一本字典其中每四个元素
listA
是其成员的listB
。 You can do this using python's list slicing, and using a generator function: 您可以使用python的列表切片和生成器函数来执行此操作:
s = len(listB)
output = {listB[i]: listA[i::s] for i in range(s)}
This should be fairly straightforward. 这应该很简单。 The fancy list slicing thing is
listA[i::s]
, which takes every s
th element of listA
, starting from the i
th element. 奇特的列表切片对象是
listA[i::s]
,它从第i
个元素开始获取listA
s
第s
个元素。
You can use the following dict constructor with a zip of the keys and a list of sliced sub-lists: 您可以将以下dict构造函数与键的zip和切片的子列表的列表一起使用:
print(dict(zip(listB, [listA[i::len(listB)] for i in range(len(listB))])))
This outputs: 输出:
{'host1': ['2', '10', '18', '26'], 'host2': ['4', '12', '20', '28'], 'host3': ['6', '14', '22'], 'host4': ['8', '16', '24']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.