[英]How to find the -index of an element of a list?
Having a list like my_list
, I would like to find the -index of an element, meaning the place of the element counting from the end of the list.有一个像my_list
这样的列表,我想找到一个元素的 -index,意思是从列表末尾开始计数的元素的位置。
my_list = ['a', 'b', 'c']
For example, I want to find as a result that the -index of 'b' is -2
.例如,我想结果发现 'b' 的 -index 是-2
。
Just another way...只是另一种方式...
>>> ~my_list[::-1].index('b')
-2
This also supports finding the last occurrence if there are several.如果有多个,这也支持查找最后一次出现。
And if the list is long and the element is near the end, for example like ['z'] * 1000 + ['a', 'b', 'c']
, then it might be faster (18 μs vs 57 μs of the index - len
solution).如果列表很长并且元素接近末尾,例如['z'] * 1000 + ['a', 'b', 'c']
,那么它可能会更快(18 μs vs 57 μs的index - len
解决方案)。 Even much faster (3.1 μs):甚至更快(3.1 μs):
>>> (my_list.reverse(), ~my_list.index('b'), my_list.reverse())[1]
-2
This is algebra, not even Python.这是代数,甚至不是 Python。
Write a short table of corresponding indices, say for a table of length 10:写一个对应索引的短表,比如长度为 10 的表:
+ -
0 -10
1 -9
2 -8
...
8 -2
9 -1
This is a simple linear relationship.这是一个简单的线性关系。 Derive the equation.导出方程。 Finally, replace the constant 10
with len(my_list)
.最后,将常量10
替换为len(my_list)
。
Can you take it from there?你能从那里拿走吗?
An example of OP is ill-defined because -index
can have any of these meanings: OP 的一个示例定义不明确,因为-index
可以具有以下任何含义:
It's okay to have my_list.index('b')
subtracted from len(my_list)
and then inverse a sign of result in first case.可以从len(my_list)
减去my_list.index('b')
然后在第一种情况下反转结果的符号。
In second case we are flipping a list and applying index
method on it so -(list(reversed(my_list)).index('b) + 1)
or -(my_list[::-1].index('b') + 1)
makes it.在第二种情况下,我们正在翻转列表并对其应用index
方法,因此-(list(reversed(my_list)).index('b) + 1)
或-(my_list[::-1].index('b') + 1)
做到了。 A second way is used more often.第二种方式使用较多。
my_list = ['a', 'b', 'c', 'd'] # len(my_list) = 4
negative_index = my_list.index('b') - len(my_list) # 1 - 4 = -3
print(my_list[negative_index])
b乙
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.