※ 引述《PTT007 (优质单身好男人)》之铭言:
: 如果我有一个txt内容如下:
: 0.01
: 0.02
: 0.03
: 0.09
: 1.03
: 1.02
: 1.01
: 我想将 0.X 和 1.X 各自累加起来
: 输出结果为 0.15 和 3.06
: 我目前的做法是
: number_of_line = len(txt) # txt总共几行
: result = 0
: for i in range(2):
: for j in range(number_of_line):
: if i == int(current_row_value):
: result += current_row_value
: print result
: result = 0
: 但我这样写,资料量多的话就会跑很久
: 请问有其他较好的方法吗
: 谢谢
txt = open("input.txt")
s = txt.readline() # 先读一行进来
result1 = 0 # 一次就可以做完,loop两次干嘛?
result2 = 0
while s != '': # 检查档案尾
if s[0] == '0': # 如果你很确定只有 0 和 1 需要分开的话...
result1 += float(s)
else:
result2 += float(s)
s = txt.readline() # 进下一行
print(result1, result2)