agf1997
agf1997

Reputation: 2898

Comparing lists of different sizes and return an indices

I have 2 lists ...

The first is something like

a = [imgType_a, imgType_b, imgType_c]

The second is something like

b = [img_foo_a, img_foo_b, img_foo_c, img_bar_a, img_bar_b, img_bar_c]

I'd like to compare the lists and return a list of indices that correspond a where the last letter in a matches the last letter in b

For the example about I'd like to return ...

[0, 1, 2, 0, 1, 2]

if

a = [imgType_c, imgType_b, imgType_a]

and

b = [img_foo_a, img_foo_b, img_foo_c, img_bar_c, img_bar_a, img_bar_b, img_baz_a, img_qux_a]

the result would be

[2, 1, 0, 0, 2, 1, 2, 2]

The length of the list b will always be >=a.

Upvotes: 0

Views: 36

Answers (2)

sacuL
sacuL

Reputation: 51335

You can use index to find the index of each element in b where it matches a (once you've converted those to be just the last letter). This can be done in a list comprehension:

>>> [[i[-1] for i in a].index(x) for x in [i[-1] for i in b]]
[0, 1, 2, 0, 1, 2]

Or, more efficient and clearer, convert your arrays first:

>>> a_last = [i[-1] for i in a]
>>> b_last = [i[-1] for i in b]
>>> [a_last.index(x) for x in b_last]
[0, 1, 2, 0, 1, 2]

Upvotes: 1

PMende
PMende

Reputation: 5460

Instead of using a list, use a dictionary:

img_type_map = {img_type[-1]: i for i, img_type in enumerate(a)}
output = [img_type_map[img[-1]] for img in b]

Upvotes: 0

Related Questions