-1

如何从txt文件返回小时总和?

txt内容:

Willy,10,37,40,20,30
Georgy,30,30,29.5,5
Addi, 20,20,20
Lisy,16,16,20

在不导入任何库的情况下可以得到这样的结果吗?结果:

Willy:137
Georgy:94.5
Addi:60
Lisy:52

更新

我希望能够按名称汇总小时数,即:给定以下数据(注意两次出现Willy,我应该获得与上述相同的结果:

Willy,10,37,20
Georgy,30,30,29.5,5
Addi, 20,20,20
Lisy,16,16,20
Willy,40,30
4

5 回答 5

3

像这样的东西:

>>> with open("data2.txt") as f: 
...     for line in f:           #traverse over each line
...         spl=line.split(",")  #split the line at ","
                             #so now spl[0] is the name and spl[1:] are the hours 
...         print "{0}:{1}".format(spl[0],sum(map(float,spl[1:])))

         #sum(map(float,spl[1:])) returns the sum of hours after converting them to floats

输出:

Willy:137.0
Georgy:94.5
Addi:60.0
Lisy:52.0

编辑:对于您更新的问题:使用OrderedDict()

from collections import OrderedDict as od
with open("data2.txt") as f:
    dic=od()
    for line in f:
        spl=line.split(",")
        name,summ=spl[0],sum(float(x) for x in spl[1:])
        dic.setdefault(spl[0],[]).append(summ)
    for x,y in dic.items():
        print"{0}:{1}".format(x,sum(y))

输出:

Willy:137.0
Georgy:94.5
Addi:60.0
Lisy:52.0
于 2012-10-29T16:09:32.493 回答
2

每行总和

另一个略有不同的版本,没有花哨的进口或map.
只是splitfloat和一个列表理解。

with open('data.txt') as f:
    for l in f:
        name,hours = l.split(',',1)
        print '%s:%s' % (name, sum([float(x) for x in hours.split(',')]))

输出更新问题中的数据:

Willy:67.0
Georgy:94.5
Addi:60.0
Lisy:52.0
Willy:70.0

每人总和

如果这不是您要查找的内容(您想对具有相同名称的多行求和),您可以尝试以下基于字典的方法:

with open('data.txt') as f:
    d = {}
    for l in f:
        name,hours = l.split(',',1)
        if name in d:
            d[name] = d[name] +  int(sum([float(x) for x in hours.split(',')]))
        else:
            d[name] = int(sum([float(x) for x in hours.split(',')]))
for n in d:
    print '%s:%s' % (n, d[n])

如您所见,这结合了 Willy 的两行代码:

Willy:137.0
Georgy:94.5
Addi:60.0
Lisy:52.0
于 2012-10-29T16:19:26.013 回答
0

如果您设置在该输出上,我会使用str.splitand sumwith ast.literal_eval

import ast
with open('txt') as f:
    for line in f:
        name,data = line.split(',',1)
        print '{0}:{1}'.format(name,sum(ast.literal_eval(data)))

在这里,我在第一个逗号处将字符串拆分为 2 个字符串,然后用于ast.literal_eval将右侧的字符串转换为数字元组。你也可以做

sum(float(x) for x in data.split(','))

代替:

sum(ast.literal_eval(data))

但这总是会给你一个浮点结果(即使所有输入数字都是整数)——尽管我敢打赌没有的解决方案ast.literal_eval会执行得更快......

于 2012-10-29T16:06:57.807 回答
0

这是我的解决方案:

import csv

with open('input.txt', 'rb') as f:
    for line in csv.reader(f):
        print ':'.join((line[0], str(sum([float(e) for e in line[1:]]))))
于 2012-10-29T16:09:23.767 回答
0

使用 defaultdict 来累积给定名称的所有小时数的示例,然后对其进行迭代以显示总小时数。(你当然可以在旅途中总结,而不是建立列表,但知道确切的时间可能会在以后有用吗?)

import csv
from collections import defaultdict

name_hours = defaultdict(list)

with open('somefile') as fin:
    for row in csv.reader(fin):
        name, hours = row[0], row[1:]
        row[name].extend(map(int, hours))

print name_hours

for name, hours in name_hours.iteritems():
    print name, sum(hours)
于 2012-10-29T16:50:25.787 回答