繁体   English   中英

使用分隔符分隔行和列并将字符串转换为列表并计算文本文件中最后一列的总和,而不使用 pandas

[英]Sseparate row and columns with delimiter and convert string into list and calculate sum of the last column from text file without using pandas

2019-01-01,Cake Fudge,150,1,150
2019-01-01,Cake Fudge,150,3,450
2019-01-01,Death by Chocolate,180,1,180
2019-01-01,Vanilla Double Scoop,80,3,240
2019-01-01,Butterscotch Single Scoop,60,5,300
2019-01-01,Vanilla Single Scoop,50,5,250
2019-01-01,Cake Fudge,150,5,750
2019-01-01,Hot Chocolate Fudge,120,3,360
2019-01-01,Butterscotch Single Scoop,60,5,300
2019-01-01,Chocolate Europa Double Scoop,100,1,100
2019-01-01,Hot Chocolate Fudge,120,2,240
2019-01-01,Caramel Crunch Single Scoop,70,4,280
2019-01-01,Hot Chocolate Fudge,120,2,240
2019-01-01,Hot Chocolate Fudge,120,4,480
2019-01-01,Hot Chocolate Fudge,120,2,240
2019-01-01,Cafe Caramel,160,5,800
2019-01-01,Vanilla Double Scoop,80,2,510

这是数据,我想从文本文件中找到最后一列的总和

尝试这个:

with open('test.txt') as fp:
    data = [[int(col.strip()) if col.strip().isnumeric() else col.strip() for col in line.split(',')] for line in fp if line.strip()]
res = sum([row[-1] for row in data])

最后一列的平均值、最小值、最大值和总和的按月计算。

from collections import defaultdict
from datetime import datetime

with open('test.txt') as fp:
    data = [[int(col.strip()) if col.strip().isnumeric() else col.strip() for col in line.split(',')] for line in fp if line.strip()]

d, res = defaultdict(list), {}
for row in data:
    month = datetime.strptime(row[0], '%Y-%m-%d').strftime('%B')
    d[month].append(row[1:])
for key in d:
    values = [x[-1] for x in d[key]]
    res[key] = {'min': min(values), 'max': max(values), 'sum': sum(values), 'avg': sum(values) / len(values)}
print(res)

#{'February': {'avg': 350.0, 'max': 750, 'min': 100, 'sum': 1750}, 'January': {'avg': 261.6666666666667, 'max': 450, 'min': 150, 'sum': 1570},'March': {'avg': 425.0, 'max': 800, 'min': 240, 'sum': 2550}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM