我正在努力做的游戏面临着一个问题。在这个游戏中,玩家需要选择一个数字和投票。假设有5名玩家在投票,投票结束时,游戏会返回投票模式。我可以使用max(set(int_list), key=int_list.count)
获得模式,其中int_list
是我用来存储选票的列表。
但是如果选票列表类似于1,1,2,2,3或1,1,2,2,我得到了1作为模式,但我希望有一个条件来检查这些案例,并返回“非决定性模式”之类的信息。
模式是最常出现在一组数据值中的值。
我怎么才能达到这个条件呢?我用的是Python
发布于 2022-02-21 06:05:49
我们可以为此使用两个for循环,因为您的列表太短了。让我们假定投票结果如下:
votes = [1, 1, 2, 2, 3]
首先,通过在每个“垃圾桶”中累计计票来计算选票:
vote_count = dict()
for vote in votes:
if vote not in vote_count:
vote_count[vote] = 0
vote_count[vote] += 1 # Vote for 1 go to position 0, and so on
# `vote_count` will be equal to `{1: 2, 2: 2, 3: 1}`
然后,找出任何选项所获得的最大票数:
max_votes = max(vote_count.values())
# `max_votes` will be equal to `2`
最后,找到获得这么多选票的所有选项:
winning_values = [vote for vote, n in vote_count.items() if n == max_votes]
# Remember, votes for 1 were on position 0
您可以检查在这种情况下是否发生了领带:
if len(winning_values) > 1:
print("There was a tie")
发布于 2022-02-21 14:40:47
来自Counter
的collections
类对此非常有用。
from collections import Counter
votes = [1, 1, 2, 2, 3]
(a,count1),(_,count2) = Counter(votes).most_common(2)
if count1 == count2:
print("inconclusive mode")
else:
print("mode is",a)
它还有一个优点,那就是它所做的事情(计数)也是非常快的。
发布于 2022-02-21 15:02:42
标准库有statistics.multimode
,可以在您的情况下使用:
try:
mode, = statistics.multimode(int_list)
except ValueError:
print('inconclusive mode')
else:
print(mode)
它还有statistics.mode
,它返回第一个模式,就像您展示给我们的代码一样(除了线性时间而不是二次时间)。
https://stackoverflow.com/questions/71207415
复制相似问题