在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,并以列表的形式存储。然后检查使用集合删除重复,并检查集合的长度是否等于列表

试试这样的东西。:

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)

最新更新