finding the last occurrence of an item in a list python

家住魔仙堡 提交于 2019-12-05 06:08:19

To do it efficiently, enumerate the list in reverse order and return the index of the first matching item (or None by default), e.g.:

def PositionLast(x, s):
    for i, v in enumerate(reversed(s)):
        if v == x:
            return len(s) - i - 1  # return the index in the original list
    return None

Avoid reversing the list using slice notation (e.g. s[::-1]) as that would create a new reversed list in memory, which is not necessary for the task.

Your logic is incorrect, because you return the count if i==x and you have an extra loop at the trailing of your function.

Instead you loop over the reverse forms of enumerate of your list and return the index of first occurrence :

def PositionLast (x,s):
    return next(i for i,j in list(enumerate(s))[::-1] if j == x)

Demo:

print PositionLast (2, [2,5,2,3,5,3])
2
print PositionLast (3, [2,5,2,3,5,3])
5
print PositionLast (5, [2,5,2,3,5,3])
4

Your code is wrong, it's checking the list from the beginning and stopping at the first match, what you want is to check the list in reverse order.

def PositionLast (x,s):
    count = len(s)
    for i in s[::-1]:
        count -= 1
        if i == x:
            return count
    return None

Your first line gives you the correct answer only because of coincidence:
- Counts equal 5 when checking for the first item.
- Counts equal 4 when checking for the second item, it matches, then return 4.
- Coincidentally, this is the index of your last item.

Iterate list in reverse order and then check x. This could be an efficient way as reversing list and then finding index from beginning is resource intensive.

def PositionLast (x,s):
    for i in range(len(s)-1,0,-1):
        if s[i] == x:
            return i
    return None
def positionLast(x, L):
    answer = None
    for i,e in enumerate(L):
        if e==x: answer = i
    return answer
def positionLast(x, L):
    try: return max(i for i,e in enumerate(L) if e==x)
    except: return None

Thanks everyone for the replies and help! Unfortunately no one had the answer I was looking for but no matter I worked it out myself in the end but thank you very much all the same!

Here is the final code:

def PositionLast(x,s):

    count = -1
    position = None
    for i in s:
        count += 1
        if i == x:
            position = count
    return position

This returns the correct answers to all my tests.

Thanks, Eimear.

def lastposition(array,x):

    flag = 0
    for i in range(len(array)):
        if array[i] == int(x):
            x = i
            flag = 1
        else:
            pass
    if flag == 0:
        print 'None'
    else:
        print x

array = [2,5,2,3,5]

x = 2

lastposition(array,x)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!