简体   繁体   English

查找列表中项目的最后一次出现,不包括最后一个元素

[英]Find last occurence of item in a list excluding the last element

For some reason, this doesn't work when trying to find last occurrence excluding last element出于某种原因,这在尝试查找不包括最后一个元素的最后一次出现时不起作用

len(list) - 1 - list[::-1].index(1)

list = [3, 1, 1, 4, 1, 3, 1, 3, 1]

It needs to find index = 6它需要找到index = 6

Correct answer provided for a single list iteration.为单个列表迭代提供了正确答案。

Edited:编辑:

How to find the index of the last occurrence of number 1 in both lists with the same index?如何在具有相同索引的两个列表中找到最后一次出现数字 1 的索引?

list1 = [3, 1, 1, 4, 1, 3, 1, 3, 1]
list2 = [3, 1, 1, 4, 1, 3, 2, 3, 1]

The answer should be index = 4答案应该是 index = 4

Thank you谢谢

I think you need:我认为你需要:

If you want to ignore last element如果你想忽略最后一个元素

lis = [3, 1, 1, 4, 1, 3, 1, 3, 1]

print([i for i,v in enumerate(lis[:-1]) if v==1][-1])
# 6

EDIT编辑

l1 = [3, 1, 1, 4, 1, 3, 1, 3, 1]
l2 = [3, 1, 1, 4, 1, 3, 2, 3, 1]

ls1 = [i for i,v in enumerate(l1[:-1]) if v==1]
ls2 = [i for i,v in enumerate(l2[:-1]) if v==1]

val = None
# select the list with higer length here
for i in ls1[::-1]:
    if i in ls2:
        val = i
        break
print(val)
# 4

The extra arguments to index might help you simplify the indexing: index的额外参数可能会帮助您简化索引:

len(lst) - 1 - lst[::-1].index(1, 1)

Since a list is reversible, you can avoid reallocations by using an iterator:由于列表是可逆的,您可以使用迭代器避免重新分配:

it = reversed(lst)
next(it) # discard last element
len(lst) - 2 - next(ind for ind, elem in it if elem == 1)

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

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