python - 如何计算它在字典中出现相同字符串的次数
问题描述
我正在尝试编写“选举”。当用户首先要输入多少票时,然后写下他们想要的每个候选人。这就是我到目前为止所做的。
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()
解决方案
不要在函数中使用“打印”,而是使用“返回”,这样您就可以使用输出。
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())
推荐阅读
- elasticsearch - elasticsearch、kibana、logstash如何设置geo_point类型?
- javascript - 获取频道然后创建邀请
- c# - CollectionView.MoveCurrentToPosition(Int32) 没有将所有字段数据移动到当前位置
- reactjs - 将数据传递给下一个 vue
- wso2 - WSO2-AM 3.1.0 - 未添加负载平衡端点
- python - 在 python 中使用 pip 安装 dlib 的问题
- python - 目录名称在 for 循环中未更改
- list - Ansible:如何获取列表(stdout_lines)的值?
- flutter - Flutter SDK IO 隐私
- vb.net - VB.Net 是否可以阅读和更新图片的标签和评论?