返回列表 发帖

[问题求助] 这个数据处理,用python怎么做?

假设有这样一个文本,

11.550,已支付,2019-09-15 21:39:03,2019-12-30 13:21:35
10.870,已支付,2019-09-15 21:39:03,2019-09-16 12:51:36
10.350,已支付,2019-02-09 07:20:59,2019-02-11 10:56:55
10.010,已支付,2018-06-30 10:24:07,2018-07-02 12:32:31
10.620,已支付,2016-09-24 07:21:55,2016-09-26 11:45:12

需要得到11.55+10.87+10.35+10.01+10.62的结果。
如果读入列表的话,一共是5个列表,还有其它办法吗?

回复 1# netdzb


    提供两个方案。
ans=0
fin=open('text.txt','r')
for i in fin:
    ans+=float(i.split(',')[0])
fin.close()
print(ans)COPY
和一行极简的代码
print(sum(map(float,map(lambda i:i.split(',')[0],open('text.txt','r')))))COPY

TOP

回复 2# wujunkai


胶水真够牛的,一行解决问题了。

TOP

回复 3# netdzb


    说实话,不建议那样用。在大型程序里面,句柄没有关闭会出现各种各样的bug....

TOP

本帖最后由 sxw 于 2020-4-17 21:46 编辑

使用 raku, => raku.org
say [+] $=finish.lines».comb(/^ <( \d+ [\.\d+]? )>\,/)».[0];
=finish
11.550,已支付,2019-09-15 21:39:03,2019-12-30 13:21:35
10.870,已支付,2019-09-15 21:39:03,2019-09-16 12:51:36
10.350,已支付,2019-02-09 07:20:59,2019-02-11 10:56:55
10.010,已支付,2018-06-30 10:24:07,2018-07-02 12:32:31
10.620,已支付,2016-09-24 07:21:55,2016-09-26 11:45:12COPY
输出:53.4

TOP

用列表解析其实更短
print(sum(float(i.split(',')[0]) for i in open('test.txt')))COPY
或者 AWK
awk -F',' '{sum+=$1}END{print(sum)}' test.txtCOPY
或者 cut + paste + bc
cut -d',' -f1 test.txt | paste -sd+ | bcCOPY

TOP

返回列表