python replace None with blank in list using list Comprehensions or something else? Also a nested list solution [duplicate]

StackOverflow https://stackoverflow.com/questions/23321915

  •  10-07-2023
  •  | 
  •  

Frage

a = [None, None, '2014-04-27 17:31:17', None, None]

trying to replace None with ''

tried many times, this the closest I got. b= ['' for x in a if x==None] which gives me four '' but leaves out the date

i thought it would be b= ['' for x in a if x==None else x] but doesn't work.

what if it is nested like so:

a = [[None, None, '2014-04-27 17:31:17', None, None],[None, None, '2014-04-27 17:31:17', None, None],[None, None, '2014-04-27 17:31:17', None, None]]

Can you still use list comprehensions?

War es hilfreich?

Lösung

Just modify your code as follows:

b = ['' if x is None else x for x in a]    #and use is None instead of == None

>>> print b
['', '', '2014-04-27 17:31:17', '', '']

Explanation

For nested lists, you can do:

b = [['' if x is None else x for x in c] for c in a]

Andere Tipps

You don't even have to use a comprehension:

a = map(lambda x: '' if x == None else x, a)

You can use the or operator for this:

>>> a = [None, None, '2014-04-27 17:31:17', None, None]
>>> print [x or "" for x in a]
['', '', '2014-04-27 17:31:17', '', '']

..because the or operator works like so:

>>> None or ""
''
>>> "blah" or ""
'blah'

..although this might not be ideal, as it will replace any False'ish values, e.g:

>>> 0 or ""
''

If this is a problem in your case, the more explicit ['' if x is None else x for x in a] mentioned in sshashank124's answer which will only replace None specifically

You can use a comprehension if you know in advance how deep the list is nested (although it wouldn't be particularly readable), for arbitrary nested lists you can use a simple "recursive map" function like this:

def maprec(obj, fun):
    if isinstance(obj, list):
        return [maprec(x, fun) for x in obj]
    return fun(obj)

Usage:

new_list = maprec(nested_list, lambda x: '' if x is None else x)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top