[英]How to get index of the last item with a given value
In a list of integer values 在整数值列表中
a = [4, 8, 2, 3, 8, 5, 8, 8, 1, 4, 8, 2, 1, 3]
I have to find the index of the last item with value 8
. 我必须找到值为
8
的最后一项的索引。 Is there more elegant way to do that rather than mine: 有没有比我的方法更优雅的方法:
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
Try This: 尝试这个:
a = [4, 8, 2, 3, 8, 5, 8, 8, 1, 4, 8, 2, 1, 3]
index = len(a) - 1 - a[::-1].index(8)
Just reverse the array and find first index of element and then subtract it from length of array. 只需反转数组并找到元素的第一个索引,然后从数组的长度中减去它即可。
>>> 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
This throws StopIteration
if the list doesn't contain the search value. 如果列表不包含搜索值,则抛出
StopIteration
。
Use sorted
on all indexes of items with a value of 8
and take the last value, or using reverse = True
take the first value 对所有值为
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.