这是我的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 = {}
我知道我必须使用带有键值系统的hashtable,但是我现在还停留在这里,请帮助我,我使用python2.7。
发布于 2015-11-30 21:58:48
假定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,可以使用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和Using是最有效的,一些时间:
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
发布于 2015-11-30 22:03:24
在本例中,我将使用计数器,它是字典周围的标准库包装器,允许您轻松地计数元素。
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]))
https://stackoverflow.com/questions/34008527
复制相似问题