簡體   English   中英

Python for循環

[英]Python for-loop

我有一個txt文件,其數據如下:

(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

我需要比較每行之間第二列中的數字,然后打印具有較高RANGE編號的飛機的NAME(需要打印NAME,但必須比較並按從最高RANGE到最低RANGE的順序排序)。 到目前為止,我有這個:

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()

但是我不知道如何使用for范圍,但必須與它...

救命

使用排序

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])

盡管上述答案有效,但從長遠來看,我還是希望使用帶有heapq的namedtuples和attrgetter。 這是我會做的

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')))

您可以使用以下一個內襯語句對元素進行排序。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM