In Python, How to Index a List with Another List

In Python, how do I index a list with another list?

T = [L[i] for i in Idx]

How to find index of element of one list in another list which includes the same elements?

If you know that all the values in B are unique, one way would be to create a dictionary that maps the values in B to their indices.

b_dict = {}
for i, b in enumerate(B):
b_dict[b] = i

Then, loop over A and get all the values from b_dict.

a_indices = [b_dict[a] for a in A]

With your lists, we get

A: [1, 2, 3, 4, 5, 6]
B: [3, 4, 1, 6, 2, 5]
a_indices: [2, 4, 0, 1, 5, 3]

This solution is O(n) as opposed to the others, which are O(n^2), and will therefore be much faster on large lists.

Generating a list using another list and an index list

This will call __contains__ on every call for idx but should be reasonable for small(ish) lists.

list2 = [list1[i] if i in idx else 0 for i in range(len(list1))]

or

list2 = [e if i in idx else 0 for i, e in enumerate(list1)]

Also, do not write code like this. It is much less readable than your example. Furthermore, numpy may give you the kind of syntax you desire without sacrificing readability or speed.




import numpy as np 

...

arr1 = np.array(list1)

arr2 = np.zeros_like(list1)
arr2[idx] = arr1[idx]

Use list item index as index to another list in python

Loop through indices and pop the specified element out of removelistst.

for index in sorted(indices, reverse=True):
removelistst.pop(index)

I sort indices in reverse so that removing an element won't affect the indexes of later elements to be removed.

Create a list from another list indexes

This snippet should do what you are asking for (in a pythonic/explicit way):

list_1 = [11, 10, 7, 0, 3, 5, 8, 1, 4, 6, 9, 2]

# keep the indexes of every element
indexes = {v: idx for idx, v in enumerate(list_1)}
# return the index of every next element - if there isn't, return the index for 0
list_2 = [indexes.get(v+1, indexes[0]) for v in list_1]

How to slice a list using indexes in another list

Using itertools.pairwise:

>>> from itertools import pairwise
>>> for i, j in pairwise([0, 888, 1776, 2664, 3551, 4438]):
... print(i, j)
...
0 888
888 1776
1776 2664
2664 3551
3551 4438

What's next? I think you can solve it yourself.

Using index from a list to get another value/element in another list

Perhaps use a list_comprehension:

print([j_set[item] for i in on_going for item in range(len(e_list)) if i in e_list[item]])
#[2, 3]


Related Topics



Leave a reply



Submit