首页 > 解决方案 > 如何计算它在字典中出现相同字符串的次数

问题描述

我正在尝试编写“选举”。当用户首先要输入多少票时,然后写下他们想要的每个候选人。这就是我到目前为止所做的。

def election():

  results = {
      
  }

  number = int(input("Number of votes: "))
  n = 0 
  
  
  while n < number:

    vote = input("Choose your candidate: ")
    results[n] = vote
    n = n + 1
      
  else:
    print(results)  
      
    
election()

标签: python

解决方案


不要在函数中使用“打印”,而是使用“返回”,这样您就可以使用输出。


  results = {
      
  }

  number = int(input("Number of votes: "))
  n = 0 
  
  
  while n < number:

    vote = input("Choose your candidate: ")
    results[n] = vote
    n = n + 1
      
  else:
    return results 
      
    
x = election()

使用 Counter 类,您将获得一个字典,显示相同字符串在字典中出现的次数。

from collections import Counter
Counter(x.values())

推荐阅读