在列表python中查找项目的最后一次出现 [英] finding the last occurrence of an item in a list python

查看:291
本文介绍了在列表python中查找项目的最后一次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我目前拥有的:

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

当我尝试时:

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

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

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

这里的答案应该是2. 我对这种情况的发生感到困惑,如果有人可以解释我需要纠正的内容,我将不胜感激. 我还想用最基本的代码来完成此操作.

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.

谢谢.

推荐答案

要高效地执行此操作,请反向顺序的列表并返回第一个匹配项的索引(默认为None),例如:

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

避免使用切片符号(例如,s[::-1])来反转列表,因为那样会在内存中创建新的反转列表,这对于该任务不是必需的.

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.

这篇关于在列表python中查找项目的最后一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆