finding the last occurrence of an item in a list python

笑着哭i 提交于 2019-12-22 05:28:05

问题


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.


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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



回答5:


def positionLast(x, L):
    answer = None
    for i,e in enumerate(L):
        if e==x: answer = i
    return answer



回答6:


def positionLast(x, L):
    try: return max(i for i,e in enumerate(L) if e==x)
    except: return None



回答7:


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.




回答8:


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)


来源:https://stackoverflow.com/questions/34438901/finding-the-last-occurrence-of-an-item-in-a-list-python

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