Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to remove elements in list based on string pattern

I have a table (list of lists). An example output being the following:

table = ['dd03', 'ff0000', 'a30b32', '000000', '234fas', '00ffff', 'ffffff', '0000ff', '0200ff']

I want to remove all elements in the list that have any combinations of 'ff' in them or atleast 2/6 chars in the element being of that character.

I've done a list comprehension which does the job but it's clearly not very efficient and could surely be done with less code.

    table = [[part for part in my_list if part != 'ffffff'] for my_list in table]
    table = [[part for part in my_list if part != 'ffff00'] for my_list in table]
    table = [[part for part in my_list if part != 'ff0000'] for my_list in table]
    table = [[part for part in my_list if part != '0000ff'] for my_list in table]
    table = [[part for part in my_list if part != '00ffff'] for my_list in table]
    table = [[part for part in my_list if part != 'ffff'] for my_list in table]
    table = [[part for part in my_list if part != 'ff'] for my_list in table]
    table = [[part for part in my_list if part != 'ffff02'] for my_list in table]
    table = [[part for part in my_list if part != '0200ff'] for my_list in table]

I thought maybe set a regex variable for the pattern to find and then remove elements that match... but I'm not too familiar with this package and implementing it in this case.

Any direction would be appreciated.

Cheers

like image 229
arsenal88 Avatar asked Dec 24 '22 17:12

arsenal88


1 Answers

A simple containment check should work:

[item for item in table if 'ff' not in item]

The 'atleast 2/6' condition is quite redundant (the length is a constant 6), enough to check if item does not contain 'ff'.

like image 165
Moses Koledoye Avatar answered Feb 16 '23 18:02

Moses Koledoye