python - 为什么索引给出完全错误的输出?
问题描述
通常我使用索引来查找列表中元素的索引。我做了这个非常基本的程序,但它没有像我预期的那样显示输出。这是我的代码:
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() 返回特定值列表的第一个元素。
因此,对于像您这样的列表: [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 的值。
希望能帮助到你。
推荐阅读
- java - 在两个玩家之间创建一个骰子程序
- tfs - TFSDeleteProject 命令行
- unit-testing - 如何在 Go 中启动长时间运行的 SQLite 查询?
- javascript - 列表项的删除按钮和删除线功能 (JavaScript)
- javascript - Javascript从现有的属性值拆分创建数组
- c# - System.Net.WebClient 从 IIS 托管的 .NET Core 2.1 应用程序下载文件时出现错误
- python - 从 qrc 资源文件创建 pandas 数据框
- javascript - php无法将json数据解析为ajax
- ios - 自动管理签名后无法使用捆绑 ID
- javascript - 关于 JavaScript 执行上下文和提升的困惑