List1 = []
D = {}
def findScore(filename):
File = filename
fread = open(File, 'rU')
for line in fread:
List1 = line.split(',')[0], line.split(',')[1].split('\n')[0]
List2 = List1[0]
print List2
for index in List2:
print index
if index not in D:
D[index] = List1[1]
#print index, D[index], 'if'
else:
D[index] = D[index] + List1[1]
#print index, D[index], 'else'
return D
在上面的代码中,我打算找到每人的总分。 我正在尝试阅读具有2列&的csv文件6行(如输入中所示)进入List然后进入Dictionary,如果我遇到相同的名字,我将得分附加到上一个得分。不知何故,代码没有按预期工作。有人可以建议进行必要的纠正吗?
INPUT
name, score
A, 50
B, 40
C, 30
A, 45
B, 35
OUTPUT
name, total score
A, 95
B, 75
C, 30
D, 60
PS:我还没试过defaultdict
答案 0 :(得分:1)
from collections import defaultdict
score_dict = defaultdict(int)
with open("in.txt") as f:
f.next()
for line in f:
name,score = line.split(",")
score_dict[name] += int(score)
print(score_dict)
defaultdict(<type 'int'>, {'A': 95, 'C': 30, 'B': 75, 'D': 60})
使用您自己的代码,您需要每次都添加值:
def findScore(filename):
D = {}
File = filename
fread = open(File, 'rU')
for line in fread:
List1,List2 = line.split(',')
if List1 not in D:
D[List1] = int(List2)
else:
D[List1] += int(List2) # += to the value
return d
使用with
打开文件,因为它会自动关闭它们。
对变量使用描述性名称,对函数名称和变量使用下划线并使用小写字母:
def find_score(filename):
score_dict = defaultdict(int)
with open(filename) as f_read:
f_read.next() # skip header
for line in f_read:
name, score = line.split(',')
score_dict[name] += int(score)
return score_dict
答案 1 :(得分:-1)
设置将有助于添加相同键的值。
d = {}
a = set()
with open('foo.txt') as f:
for char in f.readlines():
char, value = char.split(', ')[0], int(char.rstrip().split(', ')[1])
if char in a:
value = d[char] + value
d[char] = value
else:
d[char] = value
a.add(char)
print d