【问题标题】:Don't understand a Python List Index不懂 Python 列表索引
【发布时间】:2016-01-20 05:59:58
【问题描述】:

所以,我不完全理解.index(),并且一直在搞乱代码块来尝试理解它,但它仍然没有点击我。

当弄乱这个列表时:

myList = [5024,3,True,6.5,12,1,2,2,2]
print(myList)
print(myList.index(2))

出来打印:6 这 6 是从哪里来的?

再举一个例子:

myList = [5024,3,True,6.5,12,1,2,2,2]
print(myList)
print(myList.index(4))

解决方法为:4 is not in list

但打印时:

myList = [5024,3,True,6.5,12,1,2,2,2]
print(myList)
print(myList.index(1))

打印:2

这是我不明白的。程序是否在计算此列表中出现 1 的次数?如果是这种情况,当尝试在此列表中使用 .index(2) 时,它会打印出 6 而不是 5

这是怎么回事?

【问题讨论】:

  • myList.index(2) 是 6,因为 myList[6] 是 2。myList.index(1) 是 2,因为 myList[2] == 1

标签: python python-3.x indexing printing


【解决方案1】:

True 被解释为 1。

由于myList.index(value) 返回value 的第一个索引,因此您将获得值:

>>> myList = [5024,3,True,6.5,12,1,2,2,2]
>>> myList.index(2)
6
>>> myList.index(1)
2

如果要查找特定索引处的值,请使用:

myList[index]

【讨论】:

  • 哦,它点击了!哇!我从来不知道 True 值被解释为整数。谢谢heemayl!
  • @Jeremy 没问题..如果这对您有帮助,请考虑通过单击我的答案左侧的勾号来接受答案,以便可以将此问题标记为已解决.. :)跨度>
  • isinstance(True, bool)isinstance(True, int) 会给你Truebool 派生自 int
【解决方案2】:

Data Structures - 如果您需要更多信息,请阅读这篇文章。

list.index(x)

返回列表中第一个项目的索引 值为 x。如果没有这样的项目是错误的。

您可以通过索引访问列表中的元素。索引从0 开始。 假设你有一个列表,让我们看看元素的索引:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]list_of_nums

[0 1 2 3 4 5 6 7 8 9 ] 索引

因此,如果您使用list_of_nums.index(3),它将返回列表中值为3的元素的第一次出现的索引,它是2

在您的情况下,myList.index(2) 返回值为2 的元素第一次出现的索引,即6

myList.index(4) 返回'4 is not in list',因为您的列表中没有值4 的元素。 myList.index(1) 返回值为True 的元素,因为它是值为1True == 1False == 0 的元素的第一次出现。

因此,如果您知道列表中的任何元素的值,您就可以找到它的索引。 您也可以使用索引来获取这样的值: myList[1] - 3

我希望现在更清楚了。

【讨论】:

  • List.index('3') 将引发异常。
  • @MarceloCantos 当然,但我的解释中没有看到它
  • 抱歉,评论已修改。
  • 这只是一个例子,意思是 op 用他的列表名称替换 List,但我做了调整,所以每个人都很高兴 :)
  • 它仍然会引发异常。
猜你喜欢
  • 1970-01-01
  • 2015-04-25
  • 2019-07-05
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
相关资源
最近更新 更多