2014-04-27 32 views
1

a = [None, None, '2014-04-27 17:31:17', None, None]Python使用列表理解或其他東西替換無空列表中的列表理解或其他?另外一個嵌套列表的解決方案

試圖與''

更換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

當您比較的東西與'None'使用'是'操作符([說明](http://stackoverflow.com/questions/14247373/python -沒有 - 我應該使用is-or)) – Alexei

+0

'None'和''''是兩個完全不同的東西;確保它在其他地方沒有影響。 –

+0

是啊,從谷歌牀單讀取空白變成'None',但是把它們放回到相同的位置,你已經將'None'改回'''',否則它將成爲'None'的頁面 – jason

回答

7

只需修改代碼如下:

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

對於嵌套列表,你可以這樣做:

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

爲嵌套列表? – jason

+0

@jason_cant_code,答案已更新。希望有助於 – sshashank124

+1

@Downvoter,爲什麼downvote?我的答案有問題嗎?請讓我知道,所以我可以改進它。謝謝 – sshashank124

4

你甚至不必使用理解:

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

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) 
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', '', ''] 

..because的or運營商的工作原理是這樣:

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

..although這可能不是理想的,因爲它會取代任何False'ish values,如:

>>> 0 or "" 
'' 

如果這是一個問題,你的case,更明確['' if x is None else x for x in a]在sshashank124的答案中提到,它將只會替代None具體