Python – 将元素列表与字典配对
有时,在处理记录时,我们可能会遇到可以有一对列表的问题,我们需要将相似的元素配对到单个键值字典。这是一个非常特殊的问题,但可以在数据域中应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + extend() + enumerate()
上述功能的组合可以用来解决这个问题。在此,我们迭代列表并使用extend() 将相似元素附加到相似键。
# Python3 code to demonstrate working of
# Pair lists elements to Dictionary
# Using loop + extend() + enumerate()
# initializing lists
test_list1 = [1, 2, 3, 1, 1, 2, 3]
test_list2 = [[4, 5], [6, 7], [2, 3], [10, 12],
[56, 43], [98, 100], [0, 13]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Pair lists elements to Dictionary
# Using loop + extend() + enumerate()
res = dict()
for idx, val in enumerate(test_list1):
if val in res:
res[val].extend(list(test_list2[idx]))
else:
res[val] = list(test_list2[idx])
# printing result
print("The Like elements compiled Dictionary is : " + str(res))
The original list 1 is : [1, 2, 3, 1, 1, 2, 3]
The original list 2 is : [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]]
The Like elements compiled Dictionary is : {1: [4, 5, 10, 12, 56, 43], 2: [6, 7, 98, 100], 3: [2, 3, 0, 13]}
方法 #2:使用defaultdict() + zip()
上述任务的组合也可以用来解决这个问题。在此,我们使用 zip() 对元素进行配对并将字典值初始化为列表以避免测试第一个值的存在。
# Python3 code to demonstrate working of
# Pair lists elements to Dictionary
# Using defaultdict() + zip()
from collections import defaultdict
# initializing lists
test_list1 = [1, 2, 3, 1, 1, 2, 3]
test_list2 = [[4, 5], [6, 7], [2, 3], [10, 12],
[56, 43], [98, 100], [0, 13]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Pair lists elements to Dictionary
# Using defaultdict() + zip()
res = defaultdict(list)
for ele1, ele2 in zip(test_list1, test_list2):
res[ele1].extend(ele2)
# printing result
print("The Like elements compiled Dictionary is : " + str(dict(res)))
The original list 1 is : [1, 2, 3, 1, 1, 2, 3]
The original list 2 is : [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]]
The Like elements compiled Dictionary is : {1: [4, 5, 10, 12, 56, 43], 2: [6, 7, 98, 100], 3: [2, 3, 0, 13]}