有没有更简单的方法来比较 Python 中数组中的数据计数?

Is there an easier way to compare the count of data in an array with each other in Python?

我需要比较存储在数组中的数据计数,以确定投票系统中的平局。


if votes.count(1) == votes.count(2) or votes.count(1) == votes.count(3) or votes.count(1) == votes.count(4) or votes.count(2) == votes.count(1) or  votes.count(2) == votes.count(3) or votes.count(2) == votes.count(4) or votes.count(3) == votes.count(1) or votes.count(3) == votes.count(4) or votes.count(3) == votes.count(2) or votes.count(4) == votes.count(1) or votes.count(4) == votes.count(3) or votes.count(4) == votes.count(2):

投票将以数字形式存储在数组中。因此,如果您要投票给第一位候选人,它将存储为“1”,依此类推。我想知道是否有更简单的方法来检查并非所有候选人之间是否存在联系,例如两个。

存储每个元素的Count,以list的形式存储。然后检查use set去重并检查set的长度是否等于list

尝试这样的事情。:

votes = [1, 1, 1, 1, 5, 5, 3, 3, 3, 4]

lst = [votes.count(x) for x in list(set(votes))]

print('No tie' if len(set(lst))==len(lst) else 'tie' )

但我建议使用字典:

vote = {'candidate1': 3, 'candidate2': 5, 'candidate3':5}

print('No tie' if len(set(list(vote.values())))==len(list(vote.values())) else 'tie')

如果您想知道票数相同的候选人,请试试这个:

vote = {'candidate1': 3, 'candidate2': 5, 'candidate3':5}

print('No tie' if len(set(list(vote.values())))==len(list(vote.values())) else 'tie')

duplicate = []

for cand, value in vote.items():
    if list(vote.values()).count(value) > 1:
        duplicate.append(cand)
    
print(duplicate)