简体   繁体   English

Python:如何将一行整数完整地求和?

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

I have several lines full of integers(from a .txt file), and I want to sum every signle integer one by one for each line. 我有几行充满整数(来自.txt文件),并且我想对每个符号整数逐行求和。

Example: 例:

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]

You could use something like this to iterate through the lines of your file and sum the numbers. 您可以使用类似的方法遍历文件各行并求和。

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

If there is a chance your lines may not be all digits the you will need to use this instead to check. 如果您的行有可能不是全部数字,则需要使用它来进行检查。

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.

相关问题 如何在 python 的一行中放置特定数量的整数? - How can I put a specific amount of integers on one line in python? 如何在 Python 的一行中输入 2 个整数? - How to input 2 integers in one line in Python? 我如何修复这个程序,该程序将列表中的所有整数相加,除了等于所述总和的整数? - How do I fix this program that adds up all the integers in a list except the one that equals said sum? 如何将一个列表中的所有整数添加到另一个列表中的整数,并在Python中以相同的顺序使用不同的长度? - How do I add all integers in one list to integers on another list with different length in the same order in Python? 如何从一个整数列表和一个布尔值列表创建一个列表? (Python) - How do I create a list from one list of integers and one list of booleans? (Python) 使用Python的多处理来计算一条长输入行的整数之和 - Using Python's multiprocessing to calculate the sum of integers from one long input line Python,json,附加到一行字典{}{}{}{}{},如何一一阅读? - Python, json, appending to one line dictionary {}{}{}{}{}, how do i read them one by one? 如何在Python 2.7中一次解码一行unicode? - How do I decode unicode one line at a time in Python 2.7? 如何使我的输入在一行中(python) - How do I make my input be in one line (python) 如何在Python的一行中编写条件for循环? - How do I write conditional for loops in one line in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM