如何在创建字典时 select 出现次数最多的元素?
How to select the most occurring element while creating a dictionary?
我想在两个数组之间创建一个映射。但是在 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}
在这种情况下如何为键 0
选择出现次数最多的元素 4
。
您可以使用 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}
您可以创建一个包含键和键值列表的字典。然后你可以遍历这个字典中的值列表,并使用 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}
我想在两个数组之间创建一个映射。但是在 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}
在这种情况下如何为键 0
选择出现次数最多的元素 4
。
您可以使用 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}
您可以创建一个包含键和键值列表的字典。然后你可以遍历这个字典中的值列表,并使用 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}