user2163463
user2163463

Reputation: 31

Python Subtract integers in List to return a value

I would like to take a large file like this in Python 2.7:

123 456 GTHGGGTH
223 567 FGRTHSYS
12933 4656832 GJWSOOOSKKSSJ
.....

and I want to read in the file line by line, disregard the third element, and subtract the second element in each line by the first element. Thus line 1 above would return 333.

I have tried this so far:

def deleteLast(list):      
    NewL = list.pop()        
    return NewL

f = open(file_name, 'r')
line = f.readline()
while line:
    L = line.split()
    L2 = deleteLast(L)
    L3 = [int(number) for number in L2]
    Length = L3[1]-L3[0]
    print Length
f.close()

But, when I try this the compiler says:

 ValueError: invalid literal for int() with base 10: 'T'

All help is appreciated.

Upvotes: 2

Views: 1039

Answers (4)

wim
wim

Reputation: 362587

That is because list.pop() is returning the "popped off" item, it doesn't return the list again.

Instead of this deleteLast function you have written, it would be better just to use a slice like this:

L2 = line.split()[0:2]

You are going to run into another problem later because your while loop isn't advancing at all. Consider using a for loop instead.

Upvotes: 2

imkost
imkost

Reputation: 8163

f = open(file_name, 'r')
for line in f.readlines():
     x, y = line.split(' ')[:2]
     print int(y) - int(x)

Upvotes: 0

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

try the following:

with open(file_name, 'r') as f:
    for line in f.readlines():
        rowData = line.split()
        left, right = map(int, rowData[:2])
        length = right - left
        print length

Or:

from operator import sub

with open(file_name, 'r') as f:
    for line in f.readlines():
        print sub(*map(int, line.split()[:2])[::-1])

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

You can try something like this :

In [8]: with open("abc") as f:     #always use with statement when handling files
   ...:     for line in f:
   ...:         x,y=map(int,line.split()[:2])
   ...:         print y-x
   ...:         
333
344
4643899

Upvotes: 1

Related Questions