Search code examples
pythonlist-comprehensionpython-re

Nested for loop in list comprehension not recognised python


I have a list of lists of which I am trying to iterate through every element. The list looks like this:

lsts = [['2020', '2019', '2018'], ['iPhone (1)', '$', '137781', '$', '142381', '$', '164888'], ['Mac (1)', '28622']]

My attempt to remove only single numbers using re from each element was as such:

new_lst = [re.sub('[0-9]{1}', '', ele) for ele in lst for lst in lsts]

However I get the following error:

NameError: name 'lst' is not defined

I was under the impression that this should work or is it not possible?

Thanks


Solution

  • Try switching the order of the for loops:

    >>> new_lst = [re.sub('[0-9]{1}', '', ele) for lst in lsts for ele in lst if len(i)]
    >>> new_lst
    ['', '', '', 'iPhone ()', '$', '', '$', '', '$', '', 'Mac ()', '']
    >>> 
    

    To not have empty strings try:

    >>> new_lst = [re.sub('[0-9]{1}', '', ele) for lst in lsts for ele in lst if (len(ele) > 1) & (not ele.isdigit())]
    >>> new_lst
    ['iPhone ()', 'Mac ()']
    >>>