Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 420
jason Avatar asked Jun 28 '26 17:06

jason


2 Answers

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]
like image 173
sshashank124 Avatar answered Jun 30 '26 08:06

sshashank124


You don't even have to use a comprehension:

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

like image 35
vinit_ivar Avatar answered Jun 30 '26 07:06

vinit_ivar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!