1

这本词典应该是取一个国家的三个字母的国家代码,即GRE代表大不列颠,然后将后面的四个连续数字作为一个元组。它应该是这样的:{GRE:(204,203,112,116)} 并继续为列表中的每个国家/地区执行此操作。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.;  

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

def medals(goldMedals):
    infile = open(goldMedals, 'r')
    medalDict = {}
    for line in infile:
        if infile[line] != 0:
            key = line[0:3]
            value = line[3:].split(',')
            medalDict[key] = value
    print(medalDict)
    infile.close()
    return medalDict

medals('GoldMedals.txt')
4

4 回答 4

0
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(','))
于 2013-07-16T18:02:49.920 回答
0

你的 for 循环应该是这样的:

next(infile)  # Skip the first line
for line in infile:
    words = line.split(',')
    medalDict[words[0]] = tuple(map(int, words[1:]))
于 2013-07-16T18:02:50.940 回答
0

主题的变体,我会将所有剩余的列转换为整数,并且我会使用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) 提供对行的偏移和命名访问的好特性:

# These both work to return the 'Games' column
results['ALG'].Games
results['ALG'][0]
于 2013-07-16T18:07:42.087 回答
0

我认为inspectorG4dget的答案是最易读的......但对于那些玩代码高尔夫的人来说:

with open('medals.txt', 'r') as infile:
    headers = infile.readline()
    dict([(i[0], tuple(i[1:])) for i in [list(line.strip().split(',')) for line in infile]])
于 2013-07-16T18:20:24.077 回答