Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements from a 2D-list based on a 1D-list

Tags:

python

list

I have 2 lists

List A (called a) : 2D list like this : [[1,'aaa'],[2,'bbb'],[3,'ccc'],[4,'ddd']]

List B (called b) : 1D list like this : ['aaa','abc','cba','acb']

I want to remove elements from the list A based on the content of list B. In the example, the expected result is :

New List C (called c) : [[2,'bbb'],[3,'ccc'],[4,'ddd']] //Since there is no element 'bbb', 'ccc' or 'ddd' in the list B

I'm currently using the following code and I find it very slow :

c = []
for elem in a:
    if elem[1] not in b:
        c.append(elem)

Is there a better way to do this removal ? Is it better to create a new list and append elements or remove elements from the orignal list ?

Thank you for your help!

like image 759
Martin Avatar asked Mar 02 '26 07:03

Martin


1 Answers

Not much faster, but perhaps more clean using a list comprehension

c = [elem for elem in a if elem[1] not in b]

If b is very large, then converting to a set will speed things up significantly since lookups in lists are in linear time O(n) but lookups in sets are in constant time O(1)

b_set = set(b)
c = [elem for elem in a if elem[1] not in b_set]

If the index-1 elements of a ('aaa', 'bbb', etc) are unique, then this might be even faster because then we can use the set difference operator -

a_dict = {k: v for v, k in a}
b_set = set(b)

set_difference = a_dict.keys() - b_set
c = [(a_dict[k]: k) for k in set_difference]
like image 113
FHTMitchell Avatar answered Mar 03 '26 22:03

FHTMitchell



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!