Re: [问题] txt内容切割加总

楼主: alibuda174 (阿哩不达)   2014-10-11 18:35:58
假设档案内容大致如下,已按照整数部分排序,中间可缺某整数区段,
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)
不知道这么写如何?
作者: wohtp (会喵喵叫的大叔)   2014-10-11 19:28:00
不是说"there is only one obvious way to do it"的吗?跟说好的不一样! XD
楼主: alibuda174 (阿哩不达)   2014-10-11 20:30:00
我觉得那是早期的口号,现在已经不适用了
作者: uranusjr (←這人是超級笨蛋)   2014-10-11 21:12:00
是 should be one, and preferably only one; 要所有事情都只有一种作法本来就不可能, 只能要求至少要有一种

Links booklink

Contact Us: admin [ a t ] ucptt.com