python - 如何将我的数据从文件输入到字典中?
问题描述
我有一个具有以下数据格式的文件:
0
65
88
11
0
11
11
我尝试编写下面的代码以创建一个字典,其中键是从 1 到 EOF 的序列,值是文件中的数据:到目前为止我编写的代码是:
hash_1 ={}
#print(hash_1)
file = open('t30.dat','r')
while True:
data =file.readline()
if not data:
break
print(int(data.strip()))
#hash_1[int(data.strip())] += 1
问题是我无法弄清楚如何做到这一点的最后一行
hash_1[int(data.strip())] += 1
我想要的输出应该是:
hash_1= {1:0,2:65,3:88,4:11,5:0,6:11,7:11}
任何帮助,将不胜感激
解决方案
功能方法:
with open('t30.dat') as f:
hash_1 = dict(enumerate(map(int, f), start=1))
推荐阅读
- python - 在 django 中以表单形式获取所需 BooleanField 的简单方法
- c++ - 如何在 Shogun 中保存/加载训练有素的模型?
- c# - 如何修剪两个已知值之间的字符串并删除任何类型的空格的所有运行并用单个空格替换它们
- rest - 管理运行 azure devops 管道的权限和务实地更改变量组的权限
- wordpress - Wordpress联系表格7条件逻辑pdf生成
- wpf - 如何从 wpf 中的遗传列表对象中查找特定字段
- serial-port - 我如何实现串行端口的 NIO 方法?
- javascript - 我怎样才能制作一个显示'-'标记x时间迭代的循环?
- graphql - 如何在联合中查询具有不同类型的相同字段?
- xslt - 在应用模板中保留不匹配的节点