我编写的代码:this is what I have so far maybe easier to read in the picture
您的代码中存在一些问题:
names, phylums, diets = [], [], []
应该在for循环之外声明for index, line in enumerate(animalsList, 1)
之前打印标题animals = ''
for i in range(len(animals))
应改为for i in range(len(phylums))
if phylum[i] == "..."
应该是if phylums[i] == "..."
outXX += "\n" + format(names[i], "10s") + diet[i]
应该是outXX += "\n" + format(names[i], "10s") + diets[i]
下面是根据您的代码修改的代码:
names, phylums, diets = [], [], []
try:
with open('animals.txt') as file:
animalsList = sorted(file.readlines())
print("{:14s} {:14s} {}".format("Name", "Diet", "Phylum"))
for index, line in enumerate(animalsList, 1):
name, phylum, diet = line.strip().split(',')
print("{:<2d} {:11s} {:14s} {}".format(index, name, diet, phylum))
names.append(name)
diets.append(diet)
phylums.append(phylum)
except IOError:
print('Error reading file')
outMa = ''
outRep = ''
outBird = ''
output = '\n\n--- Animals by Phylum ---'
for i in range(len(phylums)):
out = '\n{:10s} {}'.format(names[i], diets[i])
if phylums[i] == 'Mammal':
outMa += out
elif phylums[i] == 'Bird':
outBird += out
elif phylums[i] == 'Reptile':
outRep += out
output += '\n\nMammals\n----------'
output += outMa
output += '\n\nReptiles\n----------'
output += outRep
output += '\n\nBirds\n----------'
output += outBird
print(output)