如何在python字典中获得与一个值关联的多个键
下面是我试图修复的代码部分。我试图找到一个数字列表的模式(在我的程序中编码为前面的数字)。我有一个模式,但不是所有模式。我在其他帖子的基础上评论了我认为正确的方向 如果你只是尝试一种模式,那就相对容易了如何在python字典中获得与一个值关联的多个键,python,list,python-3.x,dictionary,Python,List,Python 3.x,Dictionary,下面是我试图修复的代码部分。我试图找到一个数字列表的模式(在我的程序中编码为前面的数字)。我有一个模式,但不是所有模式。我在其他帖子的基础上评论了我认为正确的方向 如果你只是尝试一种模式,那就相对容易了 #mode of numbers number_counts = {} for number in numbers: if number in number_counts: number_counts[number] += 1 else: numb
#mode of numbers
number_counts = {}
for number in numbers:
if number in number_counts:
number_counts[number] += 1
else:
number_counts[number] = 1
max_count=0
for number in number_counts:
if number_counts[number] > max_count:
max_count = number_counts[number]
print('Mode: ', number)
#allkeys = ''
#if number_counts[number] == max_count:
#allnumbers = allnumbers +" "+str(number)+","
#print('Mode: ', [allnumbers])
如果你真的想映射一系列的值,你可能会这样做
from collections import Counter
A = [0, 1, 2, 3, 4, 1, 1]
counts = Counter(A)
(mode, count) = counts.most_common(1)[0]
只有当
max\u count
的值发生更改时,程序才会以模式打印数字,而只有在找到计数更大的键时才会发生这种情况。如果遇到具有相同计数的键,将忽略该键,并且您永远不会看到它被打印。这是由于行if number\u counts[number]>max\u count:
——如果number\u counts[number]>=max\u count:,则应该是if number\u counts[number]>=max\u count:
然而,您的例程还有另一个问题:它在确定可能的模式为模式之前先打印这些模式——如果一个数字具有迄今为止最大的计数,而不是总的最大计数,则会打印一个数字
因此,将尝试打印模式的最后一部分更改为两部分(以max\u count=0开始的代码)。第一部分查找max_count
的值,但在第一部分完成之前无法确定该值。然后,第二部分查找具有该计数的所有数字并打印它们
顺便说一下,第一部分可以在一行中完成:
from collections import defaultdict
counts = {
0: 1,
1: 1,
2: 3,
3: 1,
}
results = defaultdict(list)
for (number, value) in counts.items():
results[value].append(number)
还有其他方法可以找到模式,但这似乎是一个练习
max_count = max(number_counts.values())