在下面的代码中,我创建了标识符a和b,它们指向具有相同值的两个单独列表,并通过其唯一ID值进行验证。
然后我将两者插入一个列表,并尝试找到b的索引,但它找到了一个索引。
In [21]: a = [3,2]
In [22]: b = [3,2]
In [23]: id(a)
Out[23]: 4368404136
In [24]: id(b)
Out[24]: 4368429352
In [25]: c = [[4,3], a, [5,7], b, [6,3]]
In [26]: c.index(a)
Out[26]: 1
In [27]: c.index(b)
Out[27]: 1
我怎么能回3? while循环可以工作,但似乎应该有一个函数。
i = 0
match = False
while (not match) and (i < len(c)):
if id(c[i]) == id(b):
print i
match = True
i += 1
答案 0 :(得分:2)
list.index()
通过相等匹配值,而不是身份。
编写一个使用循环的辅助函数很容易,使用is
operator和enumerate()
function进行测试:
def index_by_identity(lst, target):
for i, obj in enumerate(lst):
if obj is target:
return i
# no object matches
raise IndexError(target)
或者使用next()
function和generator expression:
def index_by_identity(lst, target):
try:
return next(i for i, obj in enumerate(lst) if obj is target)
except StopIteration:
# no object matches
raise IndexError(target)
演示:
>>> a = [3, 2]
>>> b = [3, 2]
>>> a is b
False
>>> c = [[4, 3], a, [5, 7], b, [6, 3]]
>>> def index_by_identity(lst, target):
... for i, obj in enumerate(lst):
... if obj is target:
... return i
... # no object matches
... raise IndexError(target)
...
>>> index_by_identity(c, b)
3
>>> def index_by_identity(lst, target):
... try:
... return next(i for i, obj in enumerate(lst) if obj is target)
... except StopIteration:
... # no object matches
... raise IndexError(target)
...
>>> index_by_identity(c, b)
3