澄清列表方法

时间:2013-10-20 17:20:22

标签: python list function methods

来自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时,这似乎才会发生:

有谁知道为什么?

2 个答案:

答案 0 :(得分:1)

这是因为True == 1

>>> True == 1
True

因此结果符合文档,即返回== True的第一个元素的索引。在这种情况下,1位于索引0

答案 1 :(得分:1)

那是因为:

>>> 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

相关:

Is it Pythonic to use bools as ints?

Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?