7

我的清单是这样的

mylist=[ " ","abc","bgt","llko","    ","hhyt","  ","      ","iuyt"]

如何删除此列表中包含字符串的所有空格?

4

10 回答 10

16

您可以使用列表理解

 new_list = [elem for elem in mylist if elem.strip()]

使用strip()保证即使只包含多个空格的字符串也会被删除。

于 2013-08-29T09:08:48.610 回答
9

filter未绑定的方法 一起使用str.strip

Python 2.x

>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> filter(str.strip, mylist)
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']

Python 3.x

>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> list(filter(str.strip, mylist))
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
于 2013-08-29T09:12:22.790 回答
4

只需将过滤器与None.

filter(None, mylist)

如果空字符串是指仅包含空格字符的字符串,则应使用:

filter(str.strip, mylist)

例子:

>>> filter(None, ['', 'abc', 'bgt', 'llko', '', 'hhyt', '', '', 'iuyt'])
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
>>> filter(str.strip, [' ', 'abc', 'bgt', 'llko', ' ', 'hhyt', ' ', ' ', 'iuyt'])
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
于 2013-08-29T09:08:59.027 回答
2

尝试使用filter(lambda x: x.strip(), mylist)

>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>>
>>> filter(lambda x: x.strip(), mylist)
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
>>>
>>> mylist=[ " ","abc","bgt","llko","    ","hhyt","  ","      ","iuyt"]
>>>
>>> filter(lambda x: x.strip(), mylist)
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
>>>
于 2013-08-29T09:08:59.160 回答
2
mylist = [x for x in [ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"] if x]

... 使用“if”子句列出理解,在这种情况下,依赖于 Python 认为空字符串(和空容器)在布尔上下文中为“假”的事实。

如果“空”是指零长度或仅包含空格,则可以将if子句更改为if x.strip()

于 2013-08-29T09:12:56.693 回答
1

我会这样做:

>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> new_list = [e for e in mylist if len(e.strip())!=0]
>>> new_list
      ['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
于 2013-08-29T09:10:15.573 回答
1

isalpha() 方法检查字符串是否仅由字母字符组成:

mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"] 
mylist = [word for word in mylist if word.isalpha()]
print mylist

Output:['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
于 2013-08-29T09:15:37.050 回答
0
mylist = [s for s in mylist if str is not " "]
于 2013-08-29T09:09:57.867 回答
0
list = ["first", "", "second"]
[x for x in list if x]

输出:['第一','第二']

按照建议缩短,下面给出相同的问题

从字符串列表中删除空字符串

于 2013-08-29T09:11:39.857 回答
0
>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> [i for i in mylist if i.strip() != '']
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
于 2013-08-29T09:15:10.153 回答