获取最近添加的项目的索引 [英] Get index of recently appended item
问题描述
是否有一种简单的方法来获取刚刚添加到列表中的项目的索引?我需要跟踪最后添加的项目.
Is there a straightforward way to get the index of an item I just appended to a list? I need to keep track of the last added item.
我想出了两种可能的解决方案:
I came up with two possible solutions:
# Workaround 1
# The last added is the one at index len(li) - 1
>> li = ['a', 'b', 'c',]
>> li.append('d')
>> last_index = len(li) - 1
>> last_item = li[len(li) - 1]
# Workaround 2
# Use of insert at index 0 so I know index of last added
>> li = ['a', 'b', 'c',]
>> li.insert(0, 'd')
>> last_item = li[0]
是否有技巧来获取附加项的索引?
Is there a trick to get the index of an appended item?
如果没有,您将使用上面的哪一个,为什么?您建议使用其他解决方法吗?
If there's not, which of the above would you use and why? Any different workaround you suggest?
推荐答案
li[-1]
是列表中的最后一项,因此是最近添加到其末尾的项:
li[-1]
is the last item in the list, and hence the one that was most recently appended to its end:
>>> li = [1, 2, 3]
>>> li.append(4)
>>> li[-1]
4
如果您需要索引而不是项目,那么len(li) - 1
就很好并且非常有效(因为len(li)
是在恒定时间内计算的-参见下文)
If you need the index, not the item, then len(li) - 1
is just fine, and very efficient (since len(li)
is computed in constant time - see below)
在CPython的源代码中,列表的len
映射到Objects/listobject.c
中的函数list_length
:
In the source of CPython, len
for lists is mapped to function list_length
in Objects/listobject.c
:
static Py_ssize_t
list_length(PyListObject *a)
{
return Py_SIZE(a);
}
Py_SIZE
只是用于访问在Include/object.h
中定义的所有Python对象的size属性的宏:
Py_SIZE
is just a macro for accessing the size attribute of all Python objects, defined in Include/object.h
:
#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
因此,len(lst)
本质上是单个指针取消引用.
Hence, len(lst)
is essentially a single pointer dereference.
这篇关于获取最近添加的项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!