Ehsan Ehsan - 1 year ago 53
Python Question

summation of data file within two for-loops

I want to sum numbers in a data file called(3.txt) containing the following numbers

1 10\
2 20\
3 30\

I would like to sum these numbers as we will see in the code and with other for loop enter a range of numbers to do sth. If we sum all terms of data file (x+y) we have 66, I mean 11+22+33=66. now I must have for i=1: (1+10*1)+ (2+20*1)+(3+30*1), but my code can not deal with this problem.

def func(x,y):
return x+h
for i in range(1,4):
with open('3.txt') as f:
for line in f:
c= list(map(float, line.split()))

#we must have in out put:
66, 1
126, 2
186, 3

for further information, i tried to change the place of "for d in range(1,4):" line to different lines in order to have correct answer but I did not have any correct answer.
And please note that this is a simple example and instead of return function as x+y we can have any function e.g. a complicated integration.

I appreciate your attention and your help.

Answer Source

You can use list-comprehension to read the numbers in the file and sum() them up, then have a for-loop to iterate through range(2,5) and multiply the number, for example:

with open('file.txt', 'r') as f:
    num = sum([int(x) for line in f for x in line.replace('\\', '').split()])
    for i in range(2, 5):
        print('{}, {}'.format(num*i, i))


132, 2
198, 3
264, 4

Few points you should know:

1- range() increments by one by default, so you don't need to use range(2, 5, 1)

2- Don't define functions inside for-loop

3- Comma in print function means you are adding another variable to print, print(a, b) will print a b you need to either use str.format() like I did in the example above, or use print(a + ', ' + b)


A more generalized code would be:

def func(x, y):
    return x + y

with open('file.txt', 'r') as f:
    result = 0
    for line in f:
        nums = line.replace('\\', '').split()
        result += func(*list(map(int, nums)))
    for i in range(2, 5):
        print('{}, {}'.format(result*i, i))

For the updated example, here is how to fix it:

def func(x,y):
    return x+y

with open('3.txt') as f:
    lst = [list(map(float, line.replace('\\', '').split())) for line in f]
    for i in range(1, 4):
        result = 0
        for elem in lst:
            result += func(*elem)*i
        print ('{}, {}'.format(result, i)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download