简体   繁体   中英

Comparing two columns in a matrix in python

I have a file containing following data:

PAIR 1MFK 1 URANIUM 82 HELIUM 112 3.6997  
PAIR 2JGH 2 PLUTONIUM 98 POTASSIUM 88 5.3003  
PAIR 345G 3 SODIUM 23 CARBON 14 1.664  
PAIR 4IG5 4 LITHIUM 82 ARGON 99 2.5506

Now, I have to find whether column 5th's value is greater than the columns 7th's value or vice versa. I used:

inp = open("filename".'r').read().strip().split('\n')
for line in map(str.split, inp):
    k = line[5]
    m = line[7]
    if k > m:
        print 'loop 1 satisfies'
    elif m > k:
         print 'loop 2 satisfies'
    else:
         print 'loop error'

But the problem is I'm getting output like:

loop 1 satisfies  
loop 1 satisfies  
loop 1 satisfies  
loop 1 satisfies  

But in case if 1st line 5th column's value 82 smaller than 7th's value. I can't understand the reason for this kind of error.
Please help.

It's because you aren't converting them to numbers first, your data is still string.

>>> '82' < '112'
False
>>> 82 < 112
True

As an aside note, the items will start counting from 0, so I think you probably meant to compare the 4th and 6th items.

It's because you are comparing Strings , convert them to integers first.

inp = open("filename",'r').read().strip().split('\n')
for line in map(str.split, inp):
  k = int(line[4]) #lists start at index 0 not 1
  m = int(line[6])
  if k > m: print 'loop 1 satisfies'
  elif m > k: print 'loop 2 satisfies'
  else: print 'loop error'

loop 2 satisfies
loop 1 satisfies
loop 1 satisfies
loop 2 satisfies

The other answers have addressed your problem of String comparison, but I'd also like to suggest that you use Python's csv module to solve your task. The columns in this file are delimited by spaces, and it's much cleaner and memory-efficient to use a csv.reader object.

The revised code would look something like:

import csv

inp = csv.reader( open("filename", "r"), delimiter=' ')
for line in inp:
    k = int(line[4]) # 5th column == index 4
    m = int(line[6]) # 7th col == index 6
    if k > m:
        print 'loop 1 satisfies'
    elif m > k:
        print 'loop 2 satisfies'
    else:
        print 'loop error'

Also note that this solves your string comparing problem, and uses proper zero-based indexing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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