📌  相关文章
📜  Python – 将列表转换为相似的键值列表

📅  最后修改于: 2022-05-13 01:54:20.082000             🧑  作者: Mango

Python – 将列表转换为相似的键值列表

给定两个列表,一个键和其他值,将其转换为具有列表值的字典,如果键根据索引映射到不同的值,则添加到其值列表中。

方法 #1:使用 zip() + 循环

这是可以执行此任务的方式之一。在此,我们使用 zip() 将键映射到所需的值,并使用循环来执行键的迭代。

Python3
# Python3 code to demonstrate working of 
# Convert Lists into Similar key value lists
# Using loop + zip()
  
# initializing lists
test_list1 = [5, 6, 6, 4, 5, 6] 
test_list2 = [8, 3, 2, 9, 10, 4]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# creating a mesh of keys with empty values list
res = {key: [] for key in test_list1}
  
# loop to iterate through keys and values
for key, val in zip(test_list1, test_list2):
    res[key].append(val)
  
# printing result 
print("The mapped dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Convert Lists into Similar key value lists
# Using defaultdict() + list comprehension + zip()
from collections import defaultdict
  
# initializing lists
test_list1 = [5, 6, 6, 4, 5, 6] 
test_list2 = [8, 3, 2, 9, 10, 4]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# creating a mesh of keys using defaultdict
res = defaultdict(list)
[res[key].append(val) for key, val in zip(test_list1, test_list2)]
  
# printing result 
print("The mapped dictionary : " + str(dict(res)))


输出
The original list 1 is : [5, 6, 6, 4, 5, 6]
The original list 2 is : [8, 3, 2, 9, 10, 4]
The mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]}

方法 #2:使用 defaultdict() + 列表理解 + zip()

上述功能的组合可以用来解决这个问题。在这种情况下,我们将任务作为一个班轮执行,并且 defaultdict() 用于使用空列表预分配值。

Python3

# Python3 code to demonstrate working of 
# Convert Lists into Similar key value lists
# Using defaultdict() + list comprehension + zip()
from collections import defaultdict
  
# initializing lists
test_list1 = [5, 6, 6, 4, 5, 6] 
test_list2 = [8, 3, 2, 9, 10, 4]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# creating a mesh of keys using defaultdict
res = defaultdict(list)
[res[key].append(val) for key, val in zip(test_list1, test_list2)]
  
# printing result 
print("The mapped dictionary : " + str(dict(res))) 
输出
The original list 1 is : [5, 6, 6, 4, 5, 6]
The original list 2 is : [8, 3, 2, 9, 10, 4]
The mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]}