简体   繁体   English

在 Python 中与 header 相加

[英]Summing numbers with header in Python

I have to write a script that does this:我必须编写一个脚本来执行此操作:

Inputfile:输入文件:
Name姓名
10 10
-43 -43
54 54
Name2名字2
654 654
43 43
2 2个
-5467 -5467
Name3名字3
65 65
65 65

Outputfile:输出文件:
Name 21姓名 21
Name2 -4768名字2 -4768
Name3 130名字3 130

I came to the conclusion that I am supposed to split the input into arrays at the names and then print the first element and the sum of the rest, but I do not know how to do it and I haven't really found anything about this on the web.我得出的结论是,我应该在名称处将输入拆分为 arrays,然后打印第一个元素和 rest 的总和,但我不知道该怎么做,而且我还没有真正找到任何相关信息在 web 上。

Some hints:一些提示:

>>> int('Name1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Name1'
>>> int('-43')
-43

That should help you figure out what is a string and what not.这应该可以帮助您弄清楚什么是字符串,什么不是。 It will also convert your input to a number for you.它还会将您的输入转换为数字。

Find out how to catch errors ( try , except ).找出如何捕捉错误( tryexcept )。

Find out how to read a file line by line.了解如何逐行读取文件。 Try iterating over the file;)尝试遍历文件;)

The rest is basic programming logic. rest 是基本的编程逻辑。 Figuring it out yourself will give you most bang for the buck.自己弄清楚会让你物有所值。

Open the files and use readline to open the files line by line.打开文件并使用 readline 逐行打开文件。 Check whether it is string or not.检查它是否是字符串。 By looking at your file format, I assume everything in between two strings (Name1 and Name2 or else) are numbers so store those on list.通过查看您的文件格式,我假设两个字符串(Name1 和 Name2 或其他)之间的所有内容都是数字,因此将它们存储在列表中。 Finally use sum(list) to get the output. I am not writing the code since this is "HOMEWORK".最后使用 sum(list) 得到 output。我没有编写代码,因为这是“家庭作业”。

Iterate over the file line by line using使用逐行遍历文件

for line in open('test.txt'):
    # do stuff

When you find a name you need to start adding each number to a sum until you encounter until you find a different name when you start to sum the numbers again from zero.当您找到一个名字时,您需要开始将每个数字加到一个总和中,直到遇到直到您从零开始再次对数字求和时找到不同的名字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM