我想在两个数组之间创建一个映射。但是在python中,这样做导致最后一个元素被选中的映射。
array_1 = [0,0,0,1,2,3]
array_2 = [4,4,5,6,8,7]
mapping = dict(zip(array_1, array_2))
print(mapping)
映射导致{0: 5, 1: 6, 2: 8, 3: 7}
在这种情况下,如何为键4
选择最常见的元素0
。
答案 0 :(得分:3)
您可以创建一个包含键和键值列表的字典。然后,您可以遍历此字典中的值列表,并使用Counter.most_common
将值更新为列表中最频繁出现的项目from collections import defaultdict, Counter
array_1 = [0,0,0,1,2,3]
array_2 = [4,4,5,6,8,7]
mapping = defaultdict(list)
#Create the mapping with a list of values
for key, value in zip(array_1, array_2):
mapping[key].append(value)
print(mapping)
#defaultdict(<class 'list'>, {0: [4, 4, 5], 1: [6], 2: [8], 3: [7]})
res = defaultdict(int)
#Iterate over mapping and chose the most frequent element in the list, and make it the value
for key, value in mapping.items():
#The most frequent element will be the first element of Counter.most_common
res[key] = Counter(value).most_common(1)[0][0]
print(dict(res))
输出将为
{0: 4, 1: 6, 2: 8, 3: 7}
答案 1 :(得分:2)
您可以使用Counter
计算所有映射的频率,然后按键和频率对这些映射进行排序:
from collections import Counter
array_1 = [0,0,0,1,2,3]
array_2 = [4,4,5,6,8,7]
c = Counter(zip(array_1, array_2))
dict(i for i, _ in sorted(c.items(), key=lambda x: (x[0], x[1]), reverse=True))
# {3: 7, 2: 8, 1: 6, 0: 4}