简体   繁体   中英

Return list of index of two lists given a third list

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]

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]

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM