Search code examples
pythonstringlistfilternumbers

Having trouble removing specific values of a list of strings


So, what Iam triyng to do is remove some specific values of a list of strings, I've tried to use regex to no sucess, i want to remove all values that doesnt have a decimal house, i cant just get the numbers from a certain index because the position of the int number varies.

Here's an example of the list

['178', '34,79', '135925,82', '135926,82']
['102021', '191', '135067,69', '858,13', '859,13']
['176054330', '12', '506', '858,13', '0,00', '1,00']

I've tried to do something like this:

re.compile(r'\d{1,5},\d{2}.*')
vend_values = list(filter(r.match, vend_name))

To get this result:

['34,79', '135925,82', '135926,82']
['135067,69', '858,13', '859,13']
['858,13', '0,00', '1,00']

But with that it ends up removing some lines as well


Solution

  • You don't need to use something as fancy as regex. In python, the in keyword will do the work for you. You can use list comprehension too:

    my_list = ['102021', '191', '135067,69', '858,13', '859,13']
    my_filtered_list = [s for s in my_list if ',' in s]
    

    if you want to turn this into a function:

    def list_sorter(input_list):
        return [s for s in input_list if ',' in s]
    

    Hope that helps!