簡體   English   中英

Python:如何將一行整數完整地求和?

[英]Python: How do I sum a line full of integers one by one?

我有幾行充滿整數(來自.txt文件),並且我想對每個符號整數逐行求和。

例:

37107287533902102798797998220837590246510135740250 line0 = sum_of_numbers
46376937677490009712648124896970078050417018260538 line1 = sum_of_numbers
74324986199524741059474233309513058123726617309629 .
91942213363574161572522430563301811072406154908250 .
23067588207539346171171980310421047513778063246676 .
89261670696623633820136378418383684178734361726757 .
28112879812849979408065481931592621691275889832738 .
44274228917432520321923589422876796487670272189318 .
47451445736001306439091167216856844588711603153276 .
70386486105843025439939619828917593665686757934951 line9 = sum_of_numbers 
f = open('foo.txt', 'r')

def sum_line(line):
  return sum(int(c) for c in line.strip())

line_sums = [sum_line(line) for line in f]

您可以使用類似的方法遍歷文件各行並求和。

with open('file.txt', 'r') as f:
    for line in f:
        print(sum(int(char) for char in line.strip()))

如果您的行有可能不是全部數字,則需要使用它來進行檢查。

print(sum(int(char) for char in line if char.isdigit()))
# no need for .strip() since \n characters are not a digit

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM