python - Python打印字典键和值除以另一个变量
问题描述
嗨,我需要打印一个字典,显示键和值除以另一个变量...我尝试过的代码的任何建议如下
#Dim variables
total_votes = 0
candidate = {}
for row in csvreader:
if row[2] in candidate.keys():
candidate[row[2]] += 1
else:
candidate[row[2]] = 1
total_votes += 1
for key, value in candidate.items():
percentage = int(value) / int(total_votes)
print((key) + " v " + (percentage))
print(f"Tolal votes {total_votes}")
解决方案
您不能将字符串和数字相加。有几个选择。
这是一个:
#Dim variables
total_votes = 0
candidate = {}
for row in csvreader:
if row[2] in candidate.keys():
candidate[row[2]] += 1
else:
candidate[row[2]] = 1
total_votes += 1
for key, value in candidate.items():
percentage = int(value)/int(total_votes)
# Using commas
print(key, " v ", percentage)
print(f"Tolal votes {total_votes}")
我注意到您还在下面使用了 f 字符串。对此有两个想法: f-strings 仅适用于更高版本的 python3。如果您在这里遇到错误,可能是因为您的版本。其次,您还可以使用 f-string 打印您的键和值:
print(f"{key} v {value}")
假设您的字典有效,这将起作用。
推荐阅读
- javascript - 文件何时完成流式传输到 AWS S3 上传 api 的事件侦听器?
- javascript - Console.log 不等待承诺
- bash - Bash:从文件名创建文件夹
- javascript - 内部函数不返回对外部函数中分配的变量的更改
- reactjs - 如何在 Material-UI 中扩展 OverridableComponent 接口
- rabbitmq - 无法使用 chef 和 testkitchen 配置 rabbitmq
- flutter - 我的可滚动列表视图有什么问题?
- python - 使用 pyparsing 解析字节字符串
- html - 防止锚链接添加到 Django 中的 url
- java - 如何在 Java 中重写和压缩