小编efc*_*fc1的帖子

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

我希望在序列'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.我很困惑这是如何发生的,如果有人能解释我需要纠正的事情,我将不胜感激.我还想用最基本的代码完成这个.

谢谢.

python position list last-occurrence

6
推荐指数
2
解决办法
5732
查看次数

标签 统计

last-occurrence ×1

list ×1

position ×1

python ×1