qsx
qsx

Reputation: 33

Python: Filter list by indices element matching another list

I have a list, of which I want to extract all elements of certain indices or the element in question being in another list:

list = ['foo', 'bar', 'spam', 'baz', 'qux']
indices = [0, -1]
other_list = ['spam']
processed_list = magic(list, indices, other_list)
processed_list == ['foo', 'spam', 'qux']

I know that I can achieve either of this with a list comprehension (something like processed_list = [list[x] for x in indices]), but I can’t find a way to combine those.

Upvotes: 1

Views: 355

Answers (2)

Kaushik NP
Kaushik NP

Reputation: 6781

A simple process :

>>> processed_list = [l[i] for i in indices]
>>> processed_list.extend([ele for ele in other_list if ele in l])

Or a single liner, though it just doesn't feel right.

>>> processed_list = [l[i] for i in indices] + [ele for ele in other_list if ele in l]

Since the elements may get duplicated, use a set later if required.

#driver values :

IN : indices = [0, -1]
IN : other_list = ['spam']
OUT : ['foo', 'qux', 'spam']

Upvotes: 0

jpp
jpp

Reputation: 164673

Here is one way. Note indexing starts at 0 in Python, so I have changed your inputs accordingly.

lst = ['foo', 'bar', 'spam', 'baz', 'qux']
indices = [0, -1]
other_list = ['spam']

def magic(lst, indices, other):

    n = len(lst)
    idx = {k if k >= 0 else n+k for k in indices}
    other = set(other)

    return [j for i, j in enumerate(lst) if (i in idx) or (j in other)]

processed_list = magic(lst, indices, other_list)

# ['foo', 'spam', 'qux']

Upvotes: 1

Related Questions