Printing one list with respect to the other in Python

Question:

I have two lists B and X. I want to create a new list B1 which basically prints the values of X with indices according to B. But instead of writing it manually, I want to do it at one step. I present the expected output.

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

X=[4.17551036e+02, 3.53856161e+02, 2.82754301e+02, 
            1.34119055e+02,6.34573886e+01, 2.08344718e+02, 1.00000000e-24]

B1=[[X[1],X[2]],[X[3],X[4]]]

The expected output is

[[3.53856161e+02,2.82754301e+02],[1.34119055e+02,6.34573886e+01]]
Asked By: RFeynman123

||

Answers:

[X[y] for y in sum(B, [])]
#[353.856161, 282.754301, 134.119055, 63.4573886]
Answered By: God Is One
for i in B:
    for j in i:
        j = X[j]

I haven’t tested this but I believe it should work

Answered By: tygzy
B1 = [[X[i] for i in indices] for indices in B]
Answered By: nickarafyllis
B1 = [["{:.8e}".format(X[i]) for i in m] for m in B]

Output:

[[3.53856161e+02,2.82754301e+02],[1.34119055e+02,6.34573886e+01]]
Answered By: Jamiu Shaibu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.