首页 > 解决方案 > 为什么索引给出完全错误的输出?

问题描述

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

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。我正在尝试获取列表中添加的最后一个元素的索引。

为什么会发生这种情况,我该如何解决这个问题?

标签: pythonpython-3.xlistindexing

解决方案


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

因此,对于像您这样的列表: [0, 0, 0, 0, 6, 5, 2, 4] list.index(0) 无论如何都会返回 0,因为第一个 0 在 liste[ 0]。

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

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

希望能帮助到你。


推荐阅读