Python:使用与另一个列表匹配的indices元素筛选列表

时间:2018-03-08 11:13:46

标签: python list filter

我有一个列表,其中我要提取某些索引的所有元素有问题的元素在另一个列表中:

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

我知道我可以通过列表理解(类似processed_list = [list[x] for x in indices])来实现其中任何一个,但我找不到合并它们的方法。

2 个答案:

答案 0 :(得分:1)

这是一种方法。注意在Python中索引从0开始,所以我相应地更改了输入。

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']

答案 1 :(得分:0)

一个简单的过程:

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

或单个衬垫,虽然它感觉不对。

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

由于元素可能会重复,因此如果需要,请稍后使用set

#driver values:

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