根据文件制作字典,每行的第一个单词是关键字,然后其他四个数字是元组值

2024-05-15 08:03:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这本词典应该取一个国家的三个字母的国家代码,即GRE代表英国,然后把它后面的四个连续数字作为元组。应该是这样的: {GRE:(204203112116)}继续为名单上的每个国家这样做。txt文件如下所示:

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 etc.;  

实际上这不是我想显示的代码是格式化的。 我需要我的程序跳过第一行,因为它是一个标题。到目前为止,我的代码是这样的:

^{pr2}$

Tags: 文件代码txtsilver字母代表数字国家
3条回答

你的for循环应该是:

next(infile)  # Skip the first line
for line in infile:
    words = line.split(',')
    medalDict[words[0]] = tuple(map(int, words[1:]))
with open('path/to/file') as infile:
    answer = {}
    for line in infile:
        k,v = line.strip().split(',',1)
        answer[k] = tuple(int(i) for i in v.split(','))

作为主题的变体,我将所有剩余的col转换为int,并使用namedtuple

from collections import namedtuple

with open('file.txt') as fin:
    # The first line names the columns
    lines = iter(fin)
    columns = lines.next().strip().split(',')
    row = namedtuple('Row', columns[1:])
    results = {}
    for line in lines:
        columns = line.strip().split(',')
        results[columns[0]] = row(*(int(c) for c in columns[1:]))

# Results is now a dict to named tuples

这有一个很好的特性:1)跳过第一行;2)提供对行的偏移和命名访问:

^{pr2}$

相关问题 更多 >