排序连接列表一个与投票编号对应的名称列表


candidate_names = ['ed','dan','ollie','poppy']
votes = [10,13,8,3]

假设我有这两个列表,我如何让代码打印出得票最多的人并并排打印他们的名字,并打印出得票最多的2-4人之间的平局并要求重新投票?任何帮助都是非常感激的,谢谢:)。

candidate_names = ['ed','dan','ollie','poppy']
votes = [10,13,8,3]
countvotes = votes.copy()
countvotes.sort()
if countvotes[-1] > countvotes[-2]:
print('There was one winner')
else:
print('There was more than one winner - Revote')
print('Most Votes received as follows')
for i in range (4):
if votes[i] == countvotes[-1]:
print(candidate_names[i], votes[i])

Countvotes对投票列表进行排序。如果最后一个票数大于倒数第二个,则只有一个赢家,否则为平局。

然后打印出得票最多的候选人名单。

candidate_names = ['ed','dan','ollie','poppy']
votes = [10,13,8,3]
tmp=list(zip(candidate_names,votes))#temporary list having names with votes
x=max(tmp, key=lambda x: x[1])#person with most votes
tmp.remove(x)#remove person with most votes from temp list
if(any(x[1] in y for y in tmp)):#to check for draws
print("there was a draw")
else:
print(x[0]," is winner")

使用

对列表排序
tmp.sort(key=lambda x:x[1],reverse=True)#person with most votes is first

最好的方法是使用dictionary

votes = map(float, input('Vote every member seperated by comma (,): ').split(',')) #seperate the input with ',' and convert every item into float
candidatesName = ['ed','dan', 'ollie','poppy'] #candidates
candidates = dict(zip(candidatesName, votes))# make into dict to get votes for each like if input was  10,13,9,1 then the dict would have been ed: 10, dan: 13 and blah blah
most_votes = max(candidates.values())#get the maximum votes in the case above, 13
most_voted = [i for i in candidates.keys() if candidates[i] == most_votes] #get the most voted guy
print("There is a tie between {} with {} votes".format(", ".join(most_voted), candidates[most_voted[0]])) if len(most_voted)-1 > 0 else print('{} won with {} votes'.format(most_voted[0].capitalize(), candidates[most_voted[0]])) #check if there's a tie if there are multiple items in most_voted