简体   繁体   English

txt文件中整数的总和

[英]Sum of Integer Numbers in a txt File

I have two txt files that contain only numbers (number per line), so I want to add line 1 + line 1 so in succession to the last line of each file. 我有两个仅包含数字(每行编号)的txt文件,因此我想添加行1 +行1,以便依次添加到每个文件的最后一行。 Each file has the same line number. 每个文件具有相同的行号。

I'm trying this way, however I can only print the first line 我正在尝试这种方式,但是我只能打印第一行

arq = open ("List1.txt")
arq2 = open ("List2.txt")

x = [linha.strip() for linha in arq]
arq.close()
y = [linha.strip() for linha in arq2]
arq2.close()

for linha in x:
    index = 0
    while index<len(x):
       result = (int(x[index]) + int(y[index]))
       index += 1
    print result

You can achieve this easily using zip . 您可以使用zip轻松实现此目的。

Change the relevant lines of code to: 将相关代码行更改为:

for x, y in zip(arq, arq2):
    result = int(x) + int(y)
    print(result)

While you should probably use zip like mentioned above, if you want to keep on using your way of doing things your problem is here 虽然您可能应该像上面提到的那样使用zip ,但是如果您想继续使用自己的工作方式,那么问题就出在这里

when you for loop in python, it's a foreach, so when you do 当您在python中for循环时,这是一个foreach,因此当您执行

for linha in x:
    print linha

linha will be the value of x[n] where n is the iteration of the loop linha将是x[n]的值,其中n是循环的迭代

anyways, to fix your code you'd do 无论如何,要修正您的代码

# no need for the for loop, pull everything back
index = 0
while index< min(len(x), len(y)): # make sure you check for both lengths in case they are not the same
    result = (int(x[index]) + int(y[index]))
    index += 1
    print result # you want to print the result inside the loop so you don't lose it on the next iteration

the proper way to do it though would be 这样做的正确方法是

for n,p in zip(x,y):
    print int(n) + int(p)

First I would get a numpy array and concatenate 首先,我将得到一个numpy数组并进行连接

import numpy as np
file1 = np.genfromtxt('file1')
file2 = np.genfromtxt('file2')
file3 = np.concatenate((file1, file2), axis=1)

then save however you see fit 然后保存,但您认为合适

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

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