jas*_*son 1 python list-comprehension
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]]
你还能使用列表推导吗?
只需修改您的代码如下:
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', '', '']
Run Code Online (Sandbox Code Playgroud)
对于嵌套列表,您可以执行以下操作:
b = [['' if x is None else x for x in c] for c in a]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6104 次 |
| 最近记录: |