【发布时间】: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