เทียบเท่ากับ 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'

มีวิธีใดในการรับสิ่งนี้โดยไม่ต้องสร้างวงวนขนาดใหญ่หรือไม่? ฉันไม่ต้องการใช้วิธีย้อนกลับหากสามารถหลีกเลี่ยงได้ เนื่องจากลำดับมีความสำคัญ และฉันยังต้องทำคณิตศาสตร์เพิ่มเติมเล็กน้อยเพื่อดูว่าวัตถุ /would/ อยู่ที่ไหน ดูเหมือนว่าจะสิ้นเปลือง

แก้ไข:

เพื่อชี้แจง ฉันต้องการหมายเลขดัชนีของรายการนี้


person Kelketek    schedule 23.03.2012    source แหล่งที่มา
comment
stackoverflow.com/questions/6890170/   -  person Martin Flucka    schedule 23.03.2012
comment
ใช้ reversed(a) เพื่อสร้างตัววนซ้ำและไม่ต้องแก้ไขรายการ   -  person Kien Truong    schedule 23.03.2012
comment
Dikei คุณช่วยยกตัวอย่างเป็นคำตอบให้ฉันได้ไหม? ฉันยินดีจะเลือกมันถ้ามันได้ผล   -  person Kelketek    schedule 23.03.2012
comment
reversed วัตถุไม่มีวิธี index()   -  person kosii    schedule 23.03.2012


คำตอบ (4)


เกี่ยวกับ:

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

แก้ไข (ใส่ฟังก์ชั่นตามที่แนะนำ):

def listRightIndex(alist, value):
    return len(alist) - alist[-1::-1].index(value) -1
person EwyynTomato    schedule 23.03.2012
comment
นี่ไม่ใช่ทางออกที่ดี ใช้งานได้ แต่สร้างสำเนาของรายการทั้งหมด ไม่สมเหตุสมผลกับการใช้งาน - person Guy; 10.10.2018

สิ่งนี้ควรจะได้ผล:

for index, item in enumerate(reversed(a)):
    if item == "hello":
        print len(a) - index - 1
        break
person Kien Truong    schedule 23.03.2012

ฉันเขียนฟังก์ชัน 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()

person steveha    schedule 23.03.2012

รองรับ 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
person mpen    schedule 09.07.2012