【问题标题】:Python item count in a for loop [duplicate]for循环中的Python项目计数[重复]
【发布时间】:2017-02-12 14:23:09
【问题描述】:

我今天早些时候在 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 吐出列表中的每个项目,这...更好,但不是我想要的。

【问题讨论】:

  • 您忘记定义count。在 for 循环之前添加 count = 0.

标签: python loops count


【解决方案1】:

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

count = 0

实现您想要的另一种更好的方法是:

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

【讨论】:

    【解决方案2】:

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

    你应该做类似的事情

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

    【讨论】:

      【解决方案3】:

      您正在尝试增加一个您从未设置过的值:

      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 存在并且count 可以用0 + 1 结果更新。

      作为更 Pythonic 的替代方案,您可以使用 enumerate() function 在循环本身中包含一个计数器:

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

      What does enumerate mean?

      【讨论】:

        猜你喜欢
        • 2010-11-14
        • 2014-07-30
        • 1970-01-01
        • 2020-10-18
        • 2018-11-04
        • 2017-04-16
        • 2022-01-23
        • 2016-10-04
        相关资源
        最近更新 更多