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 name in zoo_animals:
print("The number ",zoo_animals.count(name)," in the list is ",name)
它給了我:

The number 1 in the list is Dog
The number 1 in the list is cat
The number 1 in the list is fish
The number 1 in the list is shark
我想要的
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
uj5u.com熱心網友回復:
如果您閱讀了 count 函式的檔案,它會解釋它的作用 - 計算串列中引數的出現次數。
您想要每個專案的位置/索引,而不是計數
for idx, name in enumerate(zoo_animals):
print(f"the animal at position {idx 1} in the list is {name}")
uj5u.com熱心網友回復:
List.count(item)回傳它在串列中出現的次數,而不是在哪里。您正在尋找List.index(item)(但這是基于 0 的,因為第一個專案的索引為 0,第二個專案的索引為 1,因此您需要為此添加 1)
uj5u.com熱心網友回復:
哦,我實際上發現它有更好的東西嗎?
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 name in zoo_animals:
print("The number ", zoo_animals.index(name) 1 ," in the list is ",name)
uj5u.com熱心網友回復:
list 的 count 方法回傳提供的元素在串列中出現的頻率或次數。
使用列舉,我們同時獲取元素和它的索引。
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 i, name in enumerate(zoo_animals):
print("The number ", i 1," in the list is ",name)
輸出:
Enter an animal = aa
Enter an animal = bb
Enter an animal = cc
Enter an animal = dd
The number 1 in the list is aa
The number 2 in the list is bb
The number 3 in the list is cc
The number 4 in the list is dd
查看以下鏈接,了解有關 enumerate(<-list name->) 函式的更多資訊
https://docs.python.org/3/library/functions.html#enumerate
https://python-reference.readthedocs.io/en/latest/docs/functions/enumerate.html
問候,
uj5u.com熱心網友回復:
在您的代碼中,zoo_animals.count(name)給出串列中不同元素的計數,而不是索引。你可以這樣做。
for i in range(len(zoo_animals)):
print("The number {} in the list is {}".format(i 1,zoo_animals[i]))
輸出
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
uj5u.com熱心網友回復:
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 name in zoo_animals:
print("The number ",zoo_animals.index(name) 1," in the list is ",name)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/322303.html
