簡體   English   中英

如何獲取具有給定值的最后一項的索引

[英]How to get index of the last item with a given value

在整數值列表中

a = [4, 8, 2, 3, 8, 5, 8, 8, 1, 4, 8, 2, 1, 3]

我必須找到值為8的最后一項的索引。 有沒有比我的方法更優雅的方法:

a = [4, 8, 2, 3, 8, 5, 8, 8, 1, 4, 8, 2, 1, 3]

for i in range(len(a)-1, -1, -1):
    if a[i] == 8:
        print(i)
        break

嘗試這個:

a = [4, 8, 2, 3, 8, 5, 8, 8, 1, 4, 8, 2, 1, 3]
index = len(a) - 1 - a[::-1].index(8)

只需反轉數組並找到元素的第一個索引,然后從數組的長度中減去它即可。

>>> lst = [4, 8, 2, 3, 8, 5, 8, 8, 1, 4, 8, 2, 1, 3]
>>> next(i for i in range(len(lst)-1, -1, -1) if lst[i] == 8)
10

如果列表不包含搜索值,則拋出StopIteration

對所有值為8的項目索引使用sorted並取最后一個值,或使用reverse = True取第一個值

x = sorted(i for i, v in enumerate(a) if v == 8)[-1]

print(x) # => 10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM