for循环中的Python项目计数

新手上路,请多包涵

我今天早些时候在 Python 中试验 for 循环和列表,我有点卡在这件可能非常简单的事情上……这是我的代码:

 animals = ["hamster","cat","monkey","giraffe","dog"]

print("There are",len(animals),"animals in the list")
print("The animals are:",animals)

s1 = str(input("Input a new animal: "))
s2 = str(input("Input a new animal: "))
s3 = str(input("Input a new animal: "))

animals.append(s1)
animals.append(s2)
animals.append(s3)

print("The list now looks like this:",animals)

animals.sort()
print("This is the list in alphabetical order:")
for item in animals:
    count = count + 1

    print("Animal number",count,"in the list is",item)

计数变量无论出于何种原因都不起作用,我试图搜索此问题但找不到任何内容。它说它没有定义,但如果我输入一个普通数字或一个字符串,它就可以正常工作。 (我现在也生病了,所以我无法正常思考,所以这可能真的很简单,我只是没听懂)我是否必须制作一个新的 for 循环?因为当我这样做时:

 for item in animal:
    for i in range(1,8):
        print("Animal number",i,"in the list is",item)

它只是用数字 1-7 吐出列表中的每个项目,这是……更好,但不是我想要的。

原文由 Pali 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 354
1 个回答

您需要先定义计数,例如:

 count = 0

另一种更好的方法来实现你想要的只是:

 for count, item in enumerate(animals):
    print("Animal number", count + 1, "in the list is", item)

原文由 BPL 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题