gpt4 book ai didi

python - 如何使用字符串键和元组值从文件读入字典?

转载 作者:太空宇宙 更新时间:2023-11-04 01:26:13 25 4
gpt4 key购买 nike

对于一项作业,我正在创建一个程序,用于从文件中检索有关奥林匹克国家及其奖牌数的信息。

我的一个函数以这种格式遍历列表:

Country,Games,Gold,Silver,Bronze
AFG,13,0,0,2
ALG,15,5,2,8
ARG,40,18,24,28
ARM,10,1,2,9
ANZ,2,3,4,5

函数需要遍历这个列表,并以国家名称为键,将其余四个条目作为元组存储到字典中。

到目前为止,这是我正在使用的内容:

def medals(string):
'''takes a file, and gathers up the country codes and their medal counts
storing them into a dictionary'''

#creates an empty dictionary
medalDict = {}
#creates an empty tuple
medalCount = ()
#These following two lines remove the column headings
with open(string) as fin:
next(fin)

for eachline in fin:
code, medal_count = eachline.strip().split(',',1)
medalDict[code] = medal_count

return medalDict

现在,目的是让条目看起来像这样

{'AFG': (13, 0, 0, 2)}

相反,我得到

{'AFG': '13,0,0,2'}

看起来它被存储为一个字符串,而不是一个元组。有什么关系吗

medalDict[code] = medal_count

代码行?我不太确定如何将它整齐地转换为元组的单独整数值。

最佳答案

您将整个字符串 '13,0,0,2' 存储为值,所以

medalDict[code] = medal_count

应替换为:

medalDict[code] = tuple(medal_count.split(','))

你原来的想法是正确的,只有这一行是异常(exception)。现在发生的变化是它将 '13,0,0,2' 拆分为列表 ['13', '0', '0', '2'] 并将其转换为元组。

你也可以这样做来将内部的字符串转换成整数:

medalDict[code] = tuple([int(ele) for ele in medal_count.split(',')])

但请确保您的 medal_count 仅包含整数。

关于python - 如何使用字符串键和元组值从文件读入字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17726868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com