2012-03-23 19 views
6

有沒有一種有效的方法來查找列表中的最後一個匹配項目?當操作字符串,你可以找到與RINDEX的最後一個項目:在Python中與rindex相關聯的列表

>>> a="GEORGE" 
    >>> a.rindex("G") 
    4 

...但這種方法不適用於列表存在:

>>> a=[ "hello", "hello", "Hi." ] 
    >>> a.rindex("hello") 
    Traceback (most recent call last): 
     File "<stdin>", line 1, in <module> 
    AttributeError: 'list' object has no attribute 'rindex' 

有沒有辦法得到這個無需構建一個大循環?如果可以避免,我寧願不使用反向方法,因爲順序非常重要,而且我還需要做一些額外的數學運算來找出對象/將要發生的位置。這看起來很浪費。

編輯:

爲了澄清,我需要這個項目的索引號。

+5

http://stackoverflow.com/questions/6890170/python-how-to-find-last-occurrence-in-a-list-in-python – 2012-03-23 09:10:11

+1

使用'逆轉(a)',它創建一個反向迭代器並且不修改列表。 – Dikei 2012-03-23 09:15:16

+0

狄凱,你能舉個例子作爲答案嗎?如果它有效,我會很樂意選擇它。 – Kelketek 2012-03-23 09:17:33

回答

12

如何:

len(a) - a[-1::-1].index("hello") - 1 

編輯(放功能的建議):

def listRightIndex(alist, value): 
    return len(alist) - alist[-1::-1].index(value) -1 
+1

我喜歡它!不過,你應該將它打包在一個函數中。 – steveha 2012-03-23 09:37:59

5

這應該工作:

for index, item in enumerate(reversed(a)): 
    if item == "hello": 
     print len(a) - index - 1 
     break 
3

我寫了一個簡單的Python的功能,並在這裏它是:

def list_rindex(lst, item): 
    """ 
    Find first place item occurs in list, but starting at end of list. 
    Return index of item in list, or -1 if item not found in the list. 
    """ 
    i_max = len(lst) 
    i_limit = -i_max 
    i = -1 
    while i > i_limit: 
     if lst[i] == item: 
      return i_max + i 
     i -= 1 
    return -1 

但是當我測試它時,EwyynTomato發佈了一個更好的答案。使用「切片」機器來反轉列表並使用.index()方法。

0

支持start

def rindex(lst, val, start=None): 
    if start is None: 
     start = len(lst)-1 
    for i in xrange(start,-1,-1): 
     if lst[i] == val: 
      return i