Python – 从元组列表中分配对元素
给定一个元组列表,分配给每个元素,它的对元素来自其他相似的对。
Input : test_list = [(5, 3), (7, 5), (8, 4)]
Output : {5: [3], 7: [5], 8: [4], 4: []}
Explanation : 1st elements are paired with respective 2nd elements from all tuples.
Input : test_list = [(5, 3)]
Output : {5: [3]}
Explanation : Only one tuples, 5 paired with 3.
方法:使用 setdefault() + 循环
在此,我们使用暴力方法来解决这个问题,对每个元组进行迭代,并将每个键和值的默认值设置为空列表,如果已经存在,则将元素附加到相应的列表中。
Python3
# Python3 code to demonstrate working of
# Assign pair elements from Tuple Lists
# Using setdefault + loop
# initializing list
test_list = [(5, 3), (7, 5), (2, 7), (3, 8), (8, 4)]
# printing string
print("The original list : " + str(test_list))
# initializing dictionary
res = dict()
for key, val in test_list:
# adding to both, corresponding keys and values
res.setdefault(val, [])
res.setdefault(key, []).append(val)
# printing results
print("The resultant pairings : " + str(res))
输出
The original list : [(5, 3), (7, 5), (2, 7), (3, 8), (8, 4)]
The resultant pairings : {3: [8], 5: [3], 7: [5], 2: [7], 8: [4], 4: []}