0

Assume we have two lists, A and B. Is there a way to get the indices of elements in the list B, which are in the list A?

For example:

A = [1,2,3,4]
B = [3,4,1,2,5]

The result should be:

[2,3,0,1]

Could it be implemented without for-loop (or fast)?

yuri5
  • 11
  • 1
  • Yes, there's a way to get the indices. What have you tried so far? – Woodford Apr 27 '21 at 23:12
  • 1
    Does this answer your question? [Find indexes of common items in two python lists](https://stackoverflow.com/questions/51171314/find-indexes-of-common-items-in-two-python-lists) – Mady Daby Apr 27 '21 at 23:13
  • `[B.index(a) for a in A]` – khelwood Apr 27 '21 at 23:14
  • 1
    Do read @MadyDaby's link. You can't do it without `for` loops, but you have the `for` loop be part of a list comprehension. – Tim Roberts Apr 27 '21 at 23:15
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Show me how to solve this coding problem” is not a Stack Overflow issue. We expect you to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. Stack Overflow is not intended to replace existing documentation and tutorials. – Prune Apr 27 '21 at 23:16
  • actually i meet this problem when using pytorch:) i hope to get some inspiration from python. What i did is `[(i == B).nonzero() for i in A]` – yuri5 Apr 28 '21 at 10:58

2 Answers2

2

This should work for your use case:

result = [A.index(x) for x in B if x in A]
GabrielP
  • 777
  • 4
  • 8
0

Use index function

A = [1,2,3,4]
B = [3,4,1,2,5]
lst=[]
for i in A:
    res=B.index(i)
    lst.append(res)
print(lst)
# [2, 3, 0, 1]
DevScheffer
  • 491
  • 4
  • 15