a = [None, None, '2014-04-27 17:31:17', None, None]
尝试将None
替换为''
b= ['' for x in a if x==None]
,它给了我四个''
,但没有留下日期
我认为它会b= ['' for x in a if x==None else x]
但不起作用。
如果嵌套如下:
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]]
你还可以使用列表推导吗?
答案 0 :(得分:9)
只需修改代码如下:
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', '', '']
对于嵌套列表,您可以执行以下操作:
b = [['' if x is None else x for x in c] for c in a]
答案 1 :(得分:4)
你甚至不需要理解:
a = map(lambda x: '' if x == None else x, a)
答案 2 :(得分:4)
您可以使用or
运算符:
>>> a = [None, None, '2014-04-27 17:31:17', None, None]
>>> print [x or "" for x in a]
['', '', '2014-04-27 17:31:17', '', '']
..因为or
运算符的工作原理如下:
>>> None or ""
''
>>> "blah" or ""
'blah'
..虽然这可能不太理想,因为它会取代任何False'ish values,例如:
>>> 0 or ""
''
如果这是您的问题,则sshashank124的答案中提到的更明确的['' if x is None else x for x in a]
只会明确替换None
答案 3 :(得分:2)
如果您事先知道嵌套列表的深度(虽然它不会特别易读),您可以使用理解,对于任意嵌套列表,您可以使用这样的简单“递归映射”函数:
def maprec(obj, fun):
if isinstance(obj, list):
return [maprec(x, fun) for x in obj]
return fun(obj)
用法:
new_list = maprec(nested_list, lambda x: '' if x is None else x)