2015-09-14 58 views
0

在下面的代碼中,我創建標識符a和b,指向具有相同值的兩個單獨列表,並通過其唯一標識值進行驗證。使用帶有單獨標識符的重複值的.index()

然後,我將兩個插入到列表中,並嘗試找到b的索引,而是找到a的索引。

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 

回答

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() functiongenerator 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