[' ',' ',' ',' ', '12 21','12 34']
我有一个这样的列表,其中前几个元素是任意数量的空白。如何删除仅包含空格的元素,使列表变为['12 21', '12 34']
列表比这大得多我刚刚将其缩小,并且仅包含空格的元素数量不是固定数字。
6 回答
使用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
如果字符串完全是空白字符,该str.isspace()
方法将返回,因此您可以使用以下内容:True
lst = [x for x in lst if not x.isspace()]
由于这是一个大列表,您可能还需要考虑使用itertools
,这样您就可以忽略只有空格的项目,而不是创建一个新列表:
>>> from itertools import ifilterfalse
>>> l = [' ',' ',' ',' ', '12 21','12 34']
>>> for item in ifilterfalse(str.isspace, l):
... print item
...
12 21
12 34
如何删除仅包含空格的元素,以便列表变为
['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
所有其他解决方案都将创建列表的副本和/或检查每个元素,这是不必要的。
这是执行此操作的“功能”方式。
In [10]: a = [' ',' ',' ','12 24', '12 31']
In [11]: filter(str.strip, a)
Out[11]: ['12 24', '12 31']
这是对 的帮助filter
。
关于内置模块内置函数过滤器的帮助:
filter(...) filter(function or None, sequence) -> list, tuple, or string
返回那些 function(item) 为真的序列项。如果 function 为 None,则返回为 true 的项目。如果序列是元组或字符串,则返回相同的类型,否则返回列表。
试试这个,
a=['','',1,2,3]
b=[x for x in a if x <> '']