简体   繁体   English

获取最后一个列表项索引的最pythonic方法

[英]Most pythonic way of getting index of the last list item

Given a list: 给定一个列表:

l1 = [0, 211, 576, 941, 1307, 1672, 2037]

What is the most pythonic way of getting the index of the last element of the list. 获取列表最后一个元素的索引的最有效的方法是什么。 Given that Python lists are zero-indexed, is it: 鉴于Python列表是零索引的,是否:

len(l1) - 1

Or, is it the following which uses Python's list operations: 还是使用Python的列表操作的以下代码:

l1.index(l1[-1])

Both return the same value, that is 6. 两者都返回相同的值,即6。

Only the first is correct: 只有第一个是正确的:

>>> lst = [1, 2, 3, 4, 1]
>>> len(lst) - 1
4
>>> lst.index(lst[-1])
0

However it depends on what do you mean by "the index of the last element". 但是,这取决于“最后一个元素的索引”是什么意思。

Note that index must traverse the whole list in order to provide an answer: 请注意, index必须遍历整个列表才能提供答案:

In [1]: %%timeit lst = list(range(100000))
   ...: lst.index(lst[-1])
   ...: 
1000 loops, best of 3: 1.82 ms per loop

In [2]: %%timeit lst = list(range(100000))
len(lst)-1
   ...: 
The slowest run took 80.20 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 109 ns per loop

Note that the second timing is in nanoseconds versus milliseconds for the first one. 请注意,第二个时间单位是纳秒,而第一个时间是毫秒

You should use the first. 您应该使用第一个。 Why? 为什么?

>>> l1 = [1,2,3,4,3]
>>> l1.index(l1[-1])
2

Bakuriu's answer is great! Bakuriu的答案很好!

In addition, it should be mentioned that you rarely need this value. 另外,应该提到的是,您很少需要此值。 There are usually other and better ways to do what you want to do. 通常,还有其他更好的方法可以做您想做的事情。 Consider this answer as a sidenote :) 将此答案视为附带说明:)

As you mention, getting the last element can be done this way: 如您所述,获取最后一个元素可以通过以下方式完成:

lst = [1,2,4,2,3]
print lst[-1]  # 3

If you need to iterate over a list, you should do this: 如果需要遍历列表,则应执行以下操作:

for element in lst:
    # do something with element

If you still need the index, this is the preferred method: 如果仍然需要索引,则这是首选方法:

for i, element in enumerate(lst):
    # i is the index, element is the actual list element

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

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