Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 463
bdhar Avatar asked Dec 28 '25 02:12

bdhar


1 Answers

>>> 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)]
like image 139
agf Avatar answered Dec 30 '25 15:12

agf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!