【问题标题】:Why is index giving a completely wrong output?为什么索引给出完全错误的输出?
【发布时间】:2018-07-14 10:07:40
【问题描述】:

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

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

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

【问题讨论】:

  • index() 方法在列表中总是打印列表中第一个匹配元素的索引。所以这就是为什么你在这 3 种情况下得到相同的输出 0。
  • python 应该如何知道您要查找的 4 个零中的哪一个?它只返回第一个的索引。
  • @Aran-Fey 但我指出了,[-1]
  • 0 是 0,不管它是如何获得的。 store[-1] 的 0 和 store[-2]store[-3]store[-4] 的 0 没有区别。
  • @Aran-Fey,谢谢,我明白了,但有办法解决吗?

标签: python python-3.x list indexing


【解决方案1】:

@mahir,您可以使用以下代码获取输出。

列表中的

index() 方法总是打印列表中第一个匹配元素的索引。所以这就是为什么你在这 3 种情况下得到相同的输出 0。

您可能会在列表中看到与 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]

【讨论】:

    【解决方案2】:

    index() 返回特定值列表的 first 元素。

    因此,对于像您这样的列表:[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的值。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 2017-02-23
      • 2020-12-24
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 2015-09-12
      相关资源
      最近更新 更多