Mapping issue with multiple lists in Python

Question:

I have two lists J1 and A1. I have another list J2 with some elements from J1. I want to print corresponding values from A1 using A2. I present the current and expected output.

J1 = [1, 7, 9, 11]
A1 = [2.1,6.9,7.3,5.4]

J2 = [1, 9]
J2,A2=map(list, zip(*((a, b) for a, b in zip(J2,A1))))
print(A2)

The current output is

[2.1, 6.9]

The expected output is

[2.1, 7.3]
Asked By: rajunarlikar123

||

Answers:

J1 = [1, 7, 9, 11]
A1 = [2.1,6.9,7.3,5.4]

J2 = [1, 9]

A2 = [A1[J1.index(a)] for a in J2]
print(A2)
Answered By: quite68

Define a dict using the keys in J1 and the values in A, then use the values in J2 as keys to look up in the new dict. operator.itemgetter will be useful.

>>> from operator import itemgetter
>>> d = dict(zip(J1, A1))
>>> A2 = list(itemgetter(*J2)(d))
>>> A2
[2.1, 7.3]
Answered By: chepner

Another variation, closer to the original:

A2 = [a for a,j in zip(A1,J1) if j in J2]
Answered By: Scott Hunter
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.