简体   繁体   中英

How to sort alphabetically using the while loop in python?

I'm trying to alphabetize items in a list while removing commas so as to format the lines from the list (text file) I'm using.

i'm required to use the while loop and not sure how i can incorporate the sort function to get the lines in alphabetical order

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

I'm not sure what list you're talking about.
You can sort all the items by creating a list of them like this:

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

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