对于一项任务,我正在创建一个程序,该程序从文件中检索有关奥林匹克国家及其奖牌数的信息。
我的功能之一通过以下格式查看列表:
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(','))
您最初的想法是正确的,这是唯一的例外。现在更改的是,它将'13,0,0,2'拆分为列表['13','0','0','2']并将其转换为元组。
您还可以执行以下操作以将内部字符串转换为整数:
medalDict[code] = tuple([int(ele) for ele in medal_count.split(',')])
但是请确保您的badge_count只包含整数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句