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]
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)
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]
Another variation, closer to the original:
A2 = [a for a,j in zip(A1,J1) if j in J2]
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]
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)
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]
Another variation, closer to the original:
A2 = [a for a,j in zip(A1,J1) if j in J2]