0

I have a txt file with data like this:

(NAME|RANGE|PASSANGERS)
Airbus A330-200|12000|263
Airbus A321-200|4600|200
Airbus A320-200|5500|162
Airbus A319-100|5700|132
Embraer 190|4445|106
ATR 72-600|1529|70

and i need to compare the number in the second column between every line and then print the NAME of the plane with the higher RANGE number (Need to print the NAME but have to compare and order it from highest RANGE to lowest RANGE). So far i have this:

f = open("./dados/aeronaves.txt","r")
d=[]
c=[]
tempList=[]
for line in f:
    a =(line.strip().split('|'))
    b = c.append(a)
    d.append(int(a[1]))
    d.sort()
for i in range(0,len(c)):
    print(c[i])
    print(c[i][1])
f.close()

but i dont know how to do it with the for in range but it has to be with it...

HELP

1
  • thx @melpomene im new to this... Commented Jan 3, 2017 at 6:43

3 Answers 3

4

Using sorted

all_planes = []
f = open("./dados/aeronaves.txt","r")
for line in f.readlines()[1:]: #skip title line
    plane = line.strip().split('|')
    all_planes.append(plane)
all_planes = sorted(all_planes, key=lambda x: x[1])
for p in all_planes:
    print(p[0])
Sign up to request clarification or add additional context in comments.

14 Comments

That's not in descending order, is it? I think you need reverse=True.
yeah thats ascending order, just add a negative symbol before x[1] in the sorted statement. reverse=True works
Or use reversed().
@Ouroborus That's less efficient than just using the right sorting comparison.
That works but it skips one line in the txt file @Einstein EDIT: i failed to notice the comment on the code nvm
|
1

Although the above answers work, i would ve preferred namedtuples and attrgetter with heapq in the long run. Here is what i would ve done,

from operator import attrgetter
from collections import namedtuple
Plane = namedtuple("Plane","name range passengers")

with open('./dados/aeronaves.txt','r') as f:
    f.readline() #needed to read the first row
    planes = [Plane(*line.strip().split('|')) for line in f]

planes.sort(key=attrgetter('range'),reverse=True) #use heapq for more control
# print them all
print(planes) #or loop through and print

#use heapq for more control
import heapq
print(heapq.nsmallest(len(planes),planes,key=attrgetter('range')))

Comments

0

You can sort the elements using the following one liner statement.

sorted_list = sorted([(line.strip().split('|')) for line in f], key=lambda k: int(k[1]))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.