Filtering list of tuples based on the availability of a member in a list
I want to filter a list of tuples like [(1,22,1),(5,1,8),(8,3,4),(7,5,6)]
using a list like [1,7]
which would eventually give me the result [(1,22,1),(5,1,8),(7开发者_如何转开发,5,6)]
; since (8,3,4)
does not have either 1
or 7
, it is eliminated.
I can write a comprehensive function for this. But I am looking for a short list comprehension if possible.
Thanks.
>>> tup_list = [(1,22,1),(5,1,8),(8,3,4),(7,5,6)]
>>> filter_list = [1,7]
>>> [tup for tup in tup_list if any(i in tup for i in filter_list)]
[(1, 22, 1), (5, 1, 8), (7, 5, 6)]
try with this one :
items = [(1,22,1),(5,1,8),(8,3,4),(7,5,6)]
result = [ item for item in items if (set([1,7]) & set(item))]
>>> [(1, 22, 1), (5, 1, 8), (7, 5, 6)]
精彩评论