作者alibuda174 (阿哩不达)
看板Python
标题Re: [问题] txt内容切割加总
时间Sat Oct 11 18:35:58 2014
假设档案内容大致如下,已按照整数部分排序,中间可缺某整数区段,
0.01
0.02
0.03
0.09
1.03
1.02
1.01
1.04
1.09
3.01
3.22
3.05
4.01
4.03
4.02
5.06
5.01
5.07
7.01
7.02
其中没有2.xx的部份。
程式码如下,参考看看
def acc(f): # 这是个generator function
total = 0 # 储存某整数区段的和
n = None # 某整数区段的整数部分
for line in f:
lf = float(line.strip())
ln = int(lf)
if n == ln: # 在同个整数区段内,加起来
total += lf
else:
if not n is None:
yield total # 进入下个整数区段,yield目前的和
n = ln
total = lf
yield total
with open('test.txt', 'rt') as f: # 开档
for a in acc(f): # acc会回传某整数区段的和
print(a)
不知道这麽写如何?
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 36.225.82.237
※ 文章网址: http://webptt.com/cn.aspx?n=bbs/Python/M.1413023761.A.4B9.html
1F:→ wohtp: 不是说"there is only one obvious way to do it"的吗? 10/11 19:28
2F:→ wohtp: 跟说好的不一样! XD 10/11 19:29
3F:→ alibuda174: 我觉得那是早期的口号,现在已经不适用了 10/11 20:30
4F:→ uranusjr: 是 should be one, and preferably only one; 要所有事 10/11 21:12
5F:→ uranusjr: 情都只有一种作法本来就不可能, 只能要求至少要有一种 10/11 21:13