Reputation: 65
What is the smartest and most pythonic way to achieve this please:
input:
i1 = [A,A,B]
i2 = [x,y,x]
i3 = [0,1,2]
parameter:
list = [[A,x],[B,x],[A,y]]
(or list = [[A,B,A],[x,z,y]]
if easier)
One needs to find the index idx
when list matches i1 and i2 and output i3[idx]
output:
output = [0,2,1]
I was thinking about list comprehensions to find all occurences of (element1,element2) in i1 and i2 but I can't manage to do it:
idxs = [i for i,v in enumerate(zip(i1,i2)) if v==(x[0],x[1]) for x in list]
Upvotes: 1
Views: 46
Reputation: 13413
Your comprehension was very close,
Here I'm using an almost identical one to create a dictionary mapping a pair to an index, and then just get the indexes from it:
i1 = ['A','A','B']
i2 = ['x','y','x']
d = {tup: idx for idx,tup in enumerate(zip(i1,i2))}
list = [['A','x'],['B','x'],['A','y']]
result = [d[tuple(pair)] for pair in list]
print(result)
Output:
[0, 2, 1]
Upvotes: 3
Reputation: 1054
One way of doing this is by using a dictionary:
i1 = ['A','A','B']
i2 = ['x','y','x']
i3 = [0,1,2]
list = [['A','x'],['B','x'],['A','y']]
mapping = dict(zip(zip(i1, i2), i3))
out = [mapping[tuple(e)] for e in list]
print(out)
[0, 2, 1]
Upvotes: 2