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

问题描述 投票:6回答:8

我希望在序列'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

当我尝试:

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

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

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

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

谢谢。

python list position last-occurrence
8个回答
6
投票

为了有效地做到这一点,enumeratereverse顺序列表并返回第一个匹配项的索引(或默认为None),例如:

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])反转列表,因为这将在内存中创建新的反转列表,这对于任务来说不是必需的。


3
投票

你的逻辑是不正确的,因为如果i==x你返回计数,你在函数的尾随处有一个额外的循环。

而是循环遍历列表的枚举的反向形式并返回第一次出现的索引:

def PositionLast (x,s):
    return next(i for i,j in list(enumerate(s))[::-1] if j == x)

演示:

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

2
投票

你的代码是错误的,它从头开始检查列表并在第一个匹配时停止,你想要的是以相反的顺序检查列表。

def PositionLast (x,s):
    count = len(s)
    for i in s[::-1]:
        count -= 1
        if i == x:
            return count
    return None

你的第一行只是因为巧合才给你正确答案: - 检查第一项时,计数等于5。 - 检查第二项时计数等于4,匹配,然后返回4。 - 巧合的是,这是你最后一项的索引。


2
投票

以相反的顺序迭代列表,然后检查x。这可能是一种有效的方式,作为逆转列表,然后从头开始查找索引是资源密集型的。

def PositionLast (x,s):
    for i in range(len(s)-1,0,-1):
        if s[i] == x:
            return i
    return None

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

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

0
投票

感谢大家的回复和帮助!不幸的是,没有人得到我想要的答案,但无论我最终自己完成了什么,但非常感谢你们!

这是最终的代码:

def PositionLast(x,s):

    count = -1
    position = None
    for i in s:
        count += 1
        if i == x:
            position = count
    return position

这将返回所有测试的正确答案。

谢谢,艾美尔。


-2
投票
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)
© www.soinside.com 2019 - 2024. All rights reserved.