是否有一种直接的方式来获取我刚添加到列表中的项目的索引?我需要跟踪最后添加的项目。获取最近附加的项目的索引
我想出了两种可能的解决方案:
# 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]
有没有窍门,以获得一个附加项的指数?
如果没有,您会使用上述哪一项,为什么?你建议的任何不同的解决方法?
关于len(li)效率的好处。谢谢! – romeroqj
@horhay:因为您喜欢它,所以我直接添加了一些更详细的信息*来源* –
感谢您深入了解! :) – romeroqj