Home > Enterprise >  Locating specific indices and printing corresponding values in Python
Locating specific indices and printing corresponding values in Python

Time:08-29

I have a list I containing two indices [0,5] and [5,8]. I want to locate these indices in Ii and print corresponding values according to Iv. I present the current and expected outputs.

import numpy as np

I=[[0,5],[5,8]]

Ii=[np.array([[[ 0,  2],
        [ 0,  5],
        [ 2,  5],
        [ 5,  8],
        [ 5, 10],
        [ 8,  9],
        [ 8, 11],
        [ 9, 11],
        [10,  8]]])]

Iv=[np.array([[[0.45202266977297145],
         [0.9977806946852882 ],
         [0.5228951173127738 ],
         [1.083230383898751  ],
         [0.5533588101522955 ],
         [0.5778527989444576 ],
         [1.2288418160926498 ],
         [0.5274353540288571 ],
         [0.5818783538996267 ]]])]

A=[Iv for I in Ii]
print(A)

The current output is

[[array([[[0.45202266977297145],
        [0.9977806946852882 ],
        [0.5228951173127738 ],
        [1.083230383898751  ],
        [0.5533588101522955 ],
        [0.5778527989444576 ],
        [1.2288418160926498 ],
        [0.5274353540288571 ],
        [0.5818783538996267 ]]])]]

The expected output is

[0.9977806946852882 ],
[1.083230383898751  ],

CodePudding user response:

You can use:

[Iv[0][0][idx][0] for idx, c in enumerate(Ii[0][0]) if list(c) in I]

Result:

[0.9977806946852882, 1.083230383898751]

This code works in your specific case, where Iv contains only 1 array, and also Ii. You'll need to slightly change it to fit over 1 array in the lists.

If Iv and Ii contain over 1 array:

[score[0][idx][0] for (array, score) in list(zip(Ii, Iv)) for idx, coord in enumerate(array[0]) if list(coord) in I]
  • Related