使用Tkinter时未获得正确的代码,这是与我的输出相比应该看起来的样子

问题描述 投票:-3回答:1

我已经尝试过很多次来修复文本文件的显示,但是循环无法正常工作。我收到更多不该重复的单词。我认为我应该处理该索引,但对于如何处理该索引却非常困惑。同样在代码的底部,我想按那里的类型,饮食和对所有动物进行分类。像这样的门This is what output should look like compared to mine

我编写的代码:this is what I have so far maybe easier to read in the picture

This is the text file

输出:This is my output when i run it

python python-3.x tkinter indexing append
1个回答
0
投票

您的代码中存在一些问题:

  • [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)
© www.soinside.com 2019 - 2024. All rights reserved.