为什么索引给出的输出是完全错误的?

2024-04-24 16:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

通常我使用index来查找列表中元素的索引。我做了一个非常基本的程序,但是它没有像我预期的那样显示输出。这是我的密码:

store_1 = []
for i in range(8):
    mountain_height = int(input())
    store_1.append(mountain_height)
    print(store_1.index(store_1[-1]))

结果:

    0
   [0]
   Index: 0
   0
   [0, 0]
   Index: 0
   0
   [0, 0, 0]
   Index: 0
   0
   [0, 0, 0, 0]
   Index: 0
   6
   [0, 0, 0, 0, 6]
   Index: 4
   5
   [0, 0, 0, 0, 6, 5]
   Index: 5
   2
   [0, 0, 0, 0, 6, 5, 2]
   Index: 6
   4
   [0, 0, 0, 0, 6, 5, 2, 4]
   Index: 7

可以看到元素1、元素2和元素3给出了错误的索引,它的索引应该是1、2、3。我正在尝试获取添加到列表中的最后一个元素的索引。你知道吗

为什么会发生这种情况?我如何解决这个问题?你知道吗


Tags: storein程序元素密码列表forinput
2条回答

@mahir,您可以使用下面的代码获取输出。你知道吗

index() method on list always prints the index of first matching element in the list. So that's why you are getting same output 0 in those 3 cases.

您可以在列表中看到index()方法的相关信息,如下所示。你知道吗

>>> help(list.index)
Help on method_descriptor:

index(...)
    L.index(value, [start, [stop]]) -> integer   return first index of value.
    Raises ValueError if the value is not present.

>>>

源代码:

store_1 = []

for i in range(8):
    mountain_height = int(input())
    store_1.append(mountain_height)
    last_index = store_1.index(store_1[-1], -1)
    print('Index:', last_index)
    print(store_1)

输出:

$ python PythonEnumerate.py
0
Index: 0
[0]
0
Index: 1
[0, 0]
0
Index: 2
[0, 0, 0]
0
Index: 3
[0, 0, 0, 0]
6
Index: 4
[0, 0, 0, 0, 6]
5
Index: 5
[0, 0, 0, 0, 6, 5]
4
Index: 6
[0, 0, 0, 0, 6, 5, 4]
2
Index: 7
[0, 0, 0, 0, 6, 5, 4, 2]

index()返回特定值列表的第一个元素。你知道吗

所以,对于像您这样的列表:[0,0,0,0,6,5,2,4] 列表.索引(0)总是会返回0,因为第一个0位于liste[0]。你知道吗

另一个例子,对于这样的列表:[1,2,3,2,1] 列表索引(2) 总是返回1,而不是3。因为第一个'2'在索引1处。你知道吗

如果要区分列表中不同的0,我建议使用I的值

希望有帮助。你知道吗

相关问题 更多 >