哈希表中的 CSV 然后计算总和

CSV in hashtable then calculate sum

这是我的 csv 文件:

name;value
John;4.0
John;-15.0
John;1.0
John;-2.0
Bob;1.0
Bob;2.5
Bob;-8

我想打印这个输出:

John : 22
Bob : 11,5

22 因为 4+15+1+2=22

11,5 因为 1+2,5+8 = 11,5

重要的是忽略-符号并用正号计算总数。

我试过这个:

import csv
with open('myfile.csv', 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    for row in reader:
        print row
Hashtable = {}

我知道我必须使用具有键值系统的哈希表,但我卡在了这一点上,请帮助我,我正在使用 python 2.7.

假定 11,5 应该是 11.5,使用 defaultdict 来处理重复的键,只是 str.lstrip 任何减号和 += 每个值

import csv
from collections import defaultdict

d = defaultdict(float)
with open('test.txt', 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    next(reader) # skip header
    for name, val in reader:
        d[name] += float(val.lstrip("-"))

输出:

for k,v in d.items():
    print(k,v)
('Bob', 11.5)
('John', 22.0)

如果你出于某种原因想使用普通字典,你可以使用 dict.setdefault:

d = {}
with open('test.txt', 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    next(reader)
    for name, val in reader:
        d.setdefault(name, 0)
        d[name] += float(val.lstrip("-"))

使用 defauldict 和 lstrip 是最有效的,一些时间:

In [26]: timeit default()
100 loops, best of 3: 2.6 ms per loop

In [27]: timeit counter()
100 loops, best of 3: 3.98 ms per loop

在这种情况下我会使用 Counter,它是一个围绕字典的标准库包装器,可以让您轻松地对元素进行计数。

import csv
from collections import Counter

counter = Counter()

with open('myfile.csv', 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    reader.next() #skips the heading
    for row in reader:
        counter[row[0]] += abs(float(row[1]))

现在,如果您真的需要使用原始字典,那么您只需要稍微扩展一下计数逻辑,即而不是

counter[row[0]] += abs(float(row[1]))

my_dict = {}
...
if row[0] not in my_dict:
    my_dict[row[0]] = abs(float(row[1]))
else
    my_dict += abs(float(row[1]))

以下是调整代码以在末尾输出哈希值的方法:

import csv
out_hash = {}
with open('test.csv', 'rb') as f:
  reader = csv.reader(f, delimiter=';')
  reader.next() # Just to skip the header
  for row in reader:
    if row[0] in out_hash:
      out_hash[row[0]] += abs(float(row[1]))
    else:
      out_hash[row[0]] = abs(float(row[1]))
print out_hash

输出:

{'Bob': 11.5, 'John': 22.0}