简体   繁体   English

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

[英]finding the last occurrence of an item in a list python

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 我希望在序列's'中找到项'x'的最后一次出现,或者如果没有,则返回None,并且第一项的位置等于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: 但是,当我将'x'更改为2而不是5时,我得到:

>>>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. 答案应该是2.我很困惑这是如何发生的,如果有人能解释我需要纠正的事情,我将不胜感激。 I would also like to complete this with the most basic code possible. 我还想用最基本的代码来完成这个。

Thank you. 谢谢。

To do it efficiently, enumerate the list in reverse order and return the index of the first matching item (or None by default), eg: 要有效地执行此操作,请按相反顺序枚举列表并返回第一个匹配项的索引(默认情况下为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

Avoid reversing the list using slice notation (eg s[::-1] ) as that would create a new reversed list in memory, which is not necessary for the task. 避免使用切片表示法(例如s[::-1] )反转列表,因为这会在内存中创建一个新的反转列表,这对于任务来说不是必需的。

Your logic is incorrect, because you return the count if i==x and you have an extra loop at the trailing of your function. 你的逻辑是不正确的,因为你返回计数如果i==x并且你在函数的尾随处有一个额外的循环。

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

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. - 检查第一项时,计数等于5。
- Counts equal 4 when checking for the second item, it matches, then return 4. - 检查第二项时计数等于4,匹配,然后返回4。
- Coincidentally, this is the index of your last item. - 巧合的是,这是你最后一项的索引。

Iterate list in reverse order and then check x. 以相反的顺序迭代列表,然后检查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
def positionLast(x, L):
    answer = None
    for i,e in enumerate(L):
        if e==x: answer = i
    return answer
def positionLast(x, L):
    try: return max(i for i,e in enumerate(L) if e==x)
    except: return None

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. 谢谢,艾美尔。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM