查找列表python中项的最后一次出现

efc*_*fc1 6 python position list last-occurrence

我希望在序列's'中找到项'x'的最后一次出现,或者如果没有,则返回None,并且第一项的位置等于0

这就是我目前拥有的:

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
Run Code Online (Sandbox Code Playgroud)

当我尝试:

>>>PositionLast (5, [2,5,2,3,5])
>>> 4
Run Code Online (Sandbox Code Playgroud)

这是正确的答案.但是,当我将'x'更改为2而不是5时,我得到:

>>>PositionLast(2, [2,5,2,3,5])
>>> 5
Run Code Online (Sandbox Code Playgroud)

答案应该是2.我很困惑这是如何发生的,如果有人能解释我需要纠正的事情,我将不胜感激.我还想用最基本的代码完成这个.

谢谢.

Eug*_*ash 6

可怜的列表没有None方法,但你可以使用s[::-1]:

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
Run Code Online (Sandbox Code Playgroud)

或者等价的

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
Run Code Online (Sandbox Code Playgroud)


ins*_*get 1

def positionLast(x, L):
    answer = None
    for i,e in enumerate(L):
        if e==x: answer = i
    return answer
Run Code Online (Sandbox Code Playgroud)