簡體   English   中英

如何使用 python 中的 while 循環按字母順序排序?

[英]How to sort alphabetically using the while loop in python?

我試圖在刪除逗號的同時對列表中的項目進行字母排序,以便格式化我正在使用的列表(文本文件)中的行。

我需要使用 while 循環,但不確定如何合並排序 function 以按字母順序獲取行

# open file

try:
    f = open('animals.txt')
    print('Success, file has been read\n')
except Exception:
    print('Sorry. This file does not exist')


# display lines

print('Name\tPhylum\tDiet')
print('----\t------\t----')

inFile = open('animals.txt', 'r')
line = inFile.readline()
while (line):
    print(line, end='')
    line = inFile.readline()

我不確定你在說什么清單。
您可以通過創建一個列表來對所有項目進行排序,如下所示:

with open('animals.txt', 'r') as inFile:
    animals = []
    line = inFile.readline()
    while line:
        items = line.rstrip().split(',')
        animals.append(items)
        line = inFile.readline()

animals.sort()

print('Name\tPhylum\tDiet')
print('----\t------\t----')

for row in animals:
    print('\t'.join(row))

Output:

Name    Phylum  Diet
----    ------  ----
Bear    Mammal  Omnivore
Bobcat  Mammal  Carnivore
Caiman  Reptile Carnivore
Cheetah Mammal  Carnivore
Croc    Reptile Carnivore
Eagle   Bird    Carnivore
Elk     Mammal  Herbivore
Emu     Bird    Omnivore
Ermine  Mammal  Carnivore
Ibis    Bird    Carnivore
Iguana  Reptile Herbivore
Lizard  Reptile Omnivore
Llama   Mammal  Herbivore
Parrot  Bird    Herbivore
Racoon  Mammal  Omnivore
Turtle  Reptile Omnivore
Yak     Mammal  Herbivore

暫無
暫無

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

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