简体   繁体   中英

finding the last occurrence of an item in a list python

I wish to find the last occurrence of an item 'x' in sequence 's', or to return None if there is none and the position of the first item is equal to 0

This is what I currently have:

def PositionLast (x,s):

    count = len(s)+1
    for i in s:
        count -= 1
        if i == x:
           return count
    for i in s:
        if i != x:
           return None

When I try:

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

This is the correct answer. However when I change 'x' to 2 instead of 5 I get this:

>>>PositionLast(2, [2,5,2,3,5])
>>> 5

The answer here should be 2. I am confused as to how this is occurring, if anyone could explain to what I need to correct I would be grateful. I would also like to complete this with the most basic code possible.

Thank you.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM