如何从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
答案 0 :(得分: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
答案 1 :(得分:2)
另一个略有不同的版本,没有花哨的导入或map
只需split
,float
和列表理解。
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
答案 2 :(得分:0)
如果您设置了该输出,我会将str.split
和sum
与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
的解决方案执行得更快......
答案 3 :(得分: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:]]))))
答案 4 :(得分: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)