2013-04-22 71 views
-1

[' ',' ',' ',' ', '12 21','12 34'] 我有一個像這樣的列表,其中前幾個元素是任意數量的空白。我如何刪除只包含空格的元素,以便列表變爲['12 21', '12 34'] 該列表比我剛縮小的列表大很多,並且包含空格的元素數量不是固定的數字。擺脫列表中僅包含空格的一些元素

+0

列表中的'strip'函數:http://stackoverflow.com/a/16120943/989121 – georg 2013-04-22 16:47:50

+0

我注意到大多數人似乎將「如何刪除元素......」解釋爲「我如何創建一個沒有元素的新清單......「,這是不完全相同的事情。 – Aya 2013-04-22 16:51:58

回答

4

使用str.strip()和一個簡單的列表理解:

In [31]: lis=[' ',' ',' ',' ', '12 21','12 34'] 

In [32]: [x for x in lis if x.strip()] 
Out[32]: ['12 21', '12 34'] 

或使用filter()

In [37]: filter(str.strip,lis) 
Out[37]: ['12 21', '12 34'] 

這樣做是因爲對空字符串:

In [35]: bool(" ".strip()) 
Out[35]: False 

幫助(str.strip )

In [36]: str.strip? 
Type:  method_descriptor 
String Form:<method 'strip' of 'str' objects> 
Namespace: Python builtin 
Docstring: 
S.strip([chars]) -> string or unicode 

Return a copy of the string S with leading and trailing 
whitespace removed. 
If chars is given and not None, remove characters in chars instead. 
If chars is unicode, S will be converted to unicode before stripping 
4

str.isspace()方法將返回True一個字符串是否是完全空白字符,這樣你就可以使用以下方法:

lst = [x for x in lst if not x.isspace()] 
2

由於這是一個大名單,你可能還需要考慮使用itertools這樣就可以忽略空格唯一項目,而不是創建一個新的列表:

>>> from itertools import ifilterfalse 
>>> l = [' ',' ',' ',' ', '12 21','12 34'] 
>>> for item in ifilterfalse(str.isspace, l): 
...  print item 
... 
12 21 
12 34 
+0

使用'str.isspace'的一個小問題(Python 2)的缺點是,如果列表中存在unicode字符串,它會投訴。 – DSM 2013-04-22 16:52:20

0

我怎麼能刪除只包含空格,因此列表變得['12 21', '12 34']

鑑於空白元素總是出現在列表的開始,那麼元素...

如果您需要修改到位列表,最優化的解決辦法是這樣的......

>>> l = [' ', ' ', ' ', ' ', '12 21','12 34'] 
>>> while l[0].isspace(): del l[0] 
>>> print l 
['12 21', '12 34'] 

...或者,如果你只是想遍歷非空白元素,那麼itertools.dropwhile()似乎是最有效的方法...

>>> import itertools 
>>> l = [' ', ' ', ' ', ' ', '12 21','12 34'] 
>>> for i in itertools.dropwhile(str.isspace, l): print i 
12 21 
12 34 

所有其他解決方案將創建列表的副本和/或檢查每個元素,這是不必要的。

-1

試試這個,

a=['','',1,2,3] 
b=[x for x in a if x <> ''] 
+1

Downvote for use <<>',因爲'''''''''''''''''''''''' – Eric 2013-04-22 16:46:22

0

這裏是這樣做的 「功能性」 的方式。

In [10]: a = [' ',' ',' ','12 24', '12 31'] 
In [11]: filter(str.strip, a) 
Out[11]: ['12 24', '12 31'] 

這是filter的幫助。

幫助的內置函數濾波器模塊內置

過濾器(...) 過濾器(函數或無,序列) - >列表,元組或字符串

返回函數(item)爲true的那些序列項。如果 函數爲None,則返回true的項目。如果sequence是一個元組 或string,則返回相同的類型,否則返回一個列表。

相關問題