2

I will like to know if I can identify the position of similar values in 2 lists and use the position identified the value in a 3rd list.

v= [100,200,300,400,500,600,700,800,900,1000,1100]
x= [67,56,89,21,90,54,38,93,46,17,75]
j= [200,500,600]

I want the code to identify that value of j can be found in v[1], v[4] and v[5], and use the position of v[1], v[4] and v[5] to obtain/return the value of x[1],x[4] and x[5]. So far, I have tried:

h = set(v)&set(j) 
print(h)
CDJB
  • 14,043
  • 5
  • 29
  • 55

1 Answers1

5

You could use a list-comprehension for this:

>>> v= [100,200,300,400,500,600,700,800,900,1000,1100]
>>> x= [67,56,89,21,90,54,38,93,46,17,75]
>>> j= [200,500,600]
>>> [x[i] for i, v_ele in enumerate(v) if v_ele in j]
[56, 90, 54]

Or using your partial set intersection solution:

>>> [x[v.index(i)] for i in set(v)&set(j)]
[56, 54, 90]

Note that this does not maintain order as sets are inherently unordered. To fix this, we can sort with key as x.index:

>>> sorted([56, 54, 90], key=x.index)
[56, 90, 54]
CDJB
  • 14,043
  • 5
  • 29
  • 55