You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表输出元素序号异常:现有代码输出不符合预期该如何修改

问题原因

你原有代码中使用的zoo_animals.count(name)是列表统计方法,作用是计算指定元素在列表中出现的总次数,因为你输入的四个动物名称均不重复,所以每次调用该方法都会返回1,无法获取元素对应的位置序号。

修正方案

使用Python内置的enumerate()函数遍历列表,该函数会同时返回元素的索引和元素值,索引默认从0开始计数,将索引加1即可得到你需要的1开头的位置序号。

修正后完整代码

zoo_animals = []
zoo_animals.append(input("Enter an animal = "))
zoo_animals.append(input("Enter an animal = "))
zoo_animals.append(input("Enter an animal = "))
zoo_animals.append(input("Enter an animal = "))
for idx, name in enumerate(zoo_animals):
    print("The number ", idx + 1, " in the list is ", name)

输出效果

运行修正后的代码即可得到你期望的结果:

The number  1  in the list is  Dog
The number  2  in the list is  cat
The number  3  in the list is  fish
The number  4  in the list is  shark

内容的提问来源于stack exchange,提问作者theredaait

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:27:04