简体   繁体   中英

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 = ['a', 'b', 'c']

For example, I want to find as a result that the -index of 'b' is -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). Even much faster (3.1 μs):

>>> (my_list.reverse(), ~my_list.index('b'), my_list.reverse())[1]
-2

This is algebra, not even Python.

Write a short table of corresponding indices, say for a table of length 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) .

Can you take it from there?

An example of OP is ill-defined because -index can have any of these meanings:

  • A number of steps needed to reach the first (leftmost) item of array if stepping backwards.
  • A number of steps needed until first (righmost) item of array is met.

It's okay to have my_list.index('b') subtracted from len(my_list) and then inverse a sign of result in first case.

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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