来自 Python 文档:
list.index(x):返回列表中第一个值为 x 的项目的索引。如果没有这样的项目是错误的。
但是,以下示例在 Python shell 中返回这些:
>>> [1, 2,True, 3, 'a', 4].index(True)
0
>>> [1, 2, 3, 'a', 4].index(True)
0
如您所见,即使列表中不存在 True,它似乎也返回 0。这似乎仅在 list.index() 中的参数为 True 时才会发生:
有谁知道为什么?
这是因为True == 1:
>>> True == 1
True
所以结果与文档一致,即== True返回的第一个元素的索引。在这种情况下,它1位于 index 0。
那是因为 :
>>> True == 1
True
list.index执行相等检查,因此,它会0为您返回索引。
>>> lis = [1, 2,True, 3, 'a', 4]
>>> next(i for i, x in enumerate(lis) if x == True)
0
>>> lis = [1, 2, 3, 'a', 4]
>>> next(i for i, x in enumerate(lis) if x == True)
0
有关的: