【问题标题】:CSV in hashtable then calculate sum哈希表中的 CSV 然后计算总和
【发布时间】:2016-03-04 16:11:36
【问题描述】:

这是我的 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。

【问题讨论】:

  • 创建 john 和 bob 变量等于 0,循环时你可以这样做 if row[0]=='John': john+=abs(row[1])

标签: python python-2.7 csv hashtable


【解决方案1】:

假设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

【讨论】:

  • 为什么是for row in reader: name, val = row 而不是for name, val in reader?个人喜好?
  • @jme,不是真的,本来我在做别的事情,只是忽略了。
【解决方案2】:

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

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}

【讨论】:

  • row[0] in out_hash.keys() 是和 O(n) 操作,所以你使代码效率非常低,这违背了目的
  • @PadraicCunningham .keys() 肯定是错误的,但更新后的代码仅通过哈希而不是键数组检查几乎 O(1)。
【解决方案3】:

在这种情况下我会使用 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]))

【讨论】:

  • 你不算你是在求和,所以使用 Counter dict 没有任何优势
  • @PadraicCunningham 当然。我不知道 defaultdict 默认为 0。所以总是使用计数器来丢失 lambda。谢谢,我学到了一些新东西!
  • defaultdict 默认为零,而不是float() 默认为零。
  • 很公平。愚蠢的我。我现在明白了。
猜你喜欢
  • 2013-03-15
  • 2016-06-23
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 2018-04-14
  • 1970-01-01
  • 2022-07-06
相关资源
最近更新 更多