How to remove lists with certain words from a list of lists or list of tuples?

Viewed 112
  1. List of Lists [['b'],['d'],['e'], ['b','d','e'],['b','e'],['e','f'],['b','d']]

  2. List of tuples [('b',),('d',),('e'),('b','d','e'),('b','e'),('e','f'),('b','d')]

I would like to remove any lists or tuples that contains both the characters 'b' and 'd'. So the output should look like below.

remove lists = [['b','d']] remove tuples = [('b','d')]

Modified List of Lists [['b'],['d'],['e'], ['b','e'],['e','f']]

Modified List of tuples [('b',),('d',),('e'),('b','e'),('e','f')]

Preferrably i would like to do this for more than one combination of lists/tuples say remove lists = [[e,f],[b,d]] to remove any lists that contain characters e and f as well as b and d.

I highly appreciate any help that can be provided.

2 Answers

A simple list comprehension will suffice. Works for both list of lists and list of tuples.

abc = [['b'],['d'],['e'], ['b','d','e'],['b','e'],['e','f'],['b','d']]

# Characters to remove
rm = [['e','f'],['b','d']]

# Function takes two list of lists as input
def refine_list(mylist, stuff_to_remove):
    for to_remove in stuff_to_remove:
        mylist = [x for x in mylist if not set(to_remove).issubset(set(x))]
    return mylist

print(refine_list(abc, rm))

Output:

[['b'], ['d'], ['e'], ['b', 'e']]

I made for you an easy to read and understand code snippet that use an helper function to remove list of strings/chars/letters from either list of lists or list of tuples

please comment if you have any question, if you done know what the enumerate method does, look it up online. let me know if you manage to understand the solution

def remove_chars(lists, list_of_chars):
    result = []
    for idx, list in enumerate(lists):
        if all(letter in list for letter in list_of_chars):
            pass
        else:
            result.append(list)
    return result


list_of_lists = [['b'],['d'],['e'], ['b','d','e'],['b','e'],['e','f'],['b','d']]
list_of_tuples = [('b',), ('d',), ('e'), ('b', 'd', 'e'), ('b', 'e'), ('e', 'f'), ('b', 'd')]
letters_to_remove = ['b']

filtered_lists = remove_chars(list_of_lists, letters_to_remove)
print(filtered_lists)

filtered_tuples = remove_chars(list_of_tuples, letters_to_remove)
print(filtered_tuples)


# remove list of list of chars:
list_of_list_of_letters = [['b'],['b','d']]

for list_of_letters in list_of_list_of_letters:
    filtered_lists = remove_chars(list_of_lists, list_of_letters)
    print(filtered_lists)

    filtered_tuples = remove_chars(list_of_tuples, list_of_letters)
    print(filtered_tuples)
Related