Re: [問題] txt內容切割加總

看板Python作者 (好看你)時間9年前 (2014/10/11 00:55), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/8 (看更多)
不知道您的資料是不是至少有對整數部分做排序 以下的作法假設有對整數部分做遞增排序 另外允許某個整數跳號 IO 我用stdin。 改成with open as data, 然後 for line in data 意思也一樣。 #program begin import sys import math if __name__ == '__main__': #initial value, should be decided by data section_int = 1 section_sum = 0.0 #process begin for line in sys.stdin: try: v = float(line.strip('\n')) if v < section_int: section_sum += v else: print '%d\t%.2f'%(section_int -1 , section_sum) section_int = math.ceil(v) section_sum = v except ValueError as e: print '%s value error: %s'%(line.strip('\n'), e) print '%d\t%.2f'%(section_int -1, section_sum) #program end 另外您原本的方法遇到幾個不同的整數,就需要 scan table 幾次,應該是慢的主因。 希望能知道這個方法改善的幅度大不大,感恩。 ※ 引述《wohtp (會喵喵叫的大叔)》之銘言: : ※ 引述《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) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.230.179.158 ※ 文章網址: http://www.ptt.cc/bbs/Python/M.1412960139.A.8B2.html
文章代碼(AID): #1KE0-BYo (Python)
討論串 (同標題文章)
文章代碼(AID): #1KE0-BYo (Python)