python - 从字典中检索键并改进此代码
问题描述
我正在设置自己的练习来提高我对 Python 的理解。我想创建一个程序来计算不同团队的投票份额。我首先将团队及其相应的票数放入字典中。
我可以先显示蓝队的投票份额,然后是红队等等,但我觉得我会一遍又一遍地重复相同的代码块。可以在这里使用函数吗?
还有一种方法可以从字典中检索密钥,而不必输入“蓝队”吗?
teams = {'blue' : 32224, 'red' : 16885, 'yellow' : 2302, 'green' : 965, 'others' : 482}
total = 52858
team_vote = teams.get('blue')
vote_share = team_vote / total_votes * 100
print(f'the blue team received {team_vote} votes')
print(f'That is a vote share of {vote_share} per cent')
解决方案
尝试使用:
teams = {'blue' : 32224, 'red' : 16885, 'yellow' : 2302, 'green' : 965, 'others' : 482}
total = 52858
team_vote = teams.get('blue')
name = {v:k for k,v in teams.items()}.get(team_vote)
vote_share = team_vote / total_votes * 100
print(f'the {name} team received {team_vote} votes')
print(f'That is a vote share of {vote_share} per cent')
推荐阅读
- logstash - 在 Logstash 中转换多维数组
- javascript - Angular 7 使用 *ngfor 对数据进行分组
- linux - 如果第一个单元格的值满足条件,如何从 CSV 中删除一行?
- python - Python监控radiusd服务。负载均衡器 tcp 健康检查
- c++ - 公式与指定值不匹配的 C++ 结果
- javascript - 使用模板替换 https 链接
- javascript - 使用 jQuery 更改滑块的值
- sql-server - 使用插入器批量运行时临时表不下降
- python-3.x - 有什么方法可以更改 tkinter 中活动选项卡的颜色吗?
- php - 带有 CSRF 令牌的 Laravel API 请求