for循环中的Python项计数

2024-05-14 13:09:19 发布

您现在位置: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)

不管是什么原因,count变量都不起作用,我试图搜索这个问题,但是什么也找不到。它说它没有定义,但如果我把一个正常的数字或字符串,它工作得很好。(我现在也病了,所以我不能正确地思考,所以这可能真的很简单,我只是没有抓住它)我需要做一个新的for循环吗?因为当我这么做的时候:

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

它只是把列表中的每一项都用数字1-7表示出来,也就是。。。更好,但不是我想要的。


Tags: theinnewforinputiscountitem
3条回答

您需要在循环之前初始化count。 否则Python不知道count是什么,因此它无法计算count + 1

你应该做些

...
count = 0
for item in animals:
    count = count + 1
    ...

首先需要定义count,如下所示:

count = 0

另一个更好的方法是:

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

您试图增加从未设置的值:

for item in animals:
    count = count + 1

Python抱怨count,因为第一次在count + 1中使用它时,count从未设置!

在循环之前将其设置为0

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

现在,第一次执行count + 1表达式时,count存在,并且可以用0 + 1结果更新count

作为一个更具python风格的替代方案,您可以使用^{} function在循环本身中包含一个计数器:

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

What does enumerate mean?

相关问题 更多 >

    热门问题