【发布时间】:2013-07-17 14:30:35
【问题描述】:
对于一项任务,我正在创建一个程序,该程序从文件中检索有关奥林匹克国家及其奖牌数量的信息。
我的一个函数通过这种格式的列表:
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
代码行?我不太确定如何将其巧妙地转换为元组的单独整数值。
【问题讨论】:
标签: python python-3.x dictionary tuples iterable-unpacking