我的列表是这样的:
mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
如何移除列表中包含空格的所有字符串?
我的列表是这样的:
mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
new_list = [elem for elem in mylist if elem.strip()]
strip()
保证了即使字符串只包含多个空格,也会被删除。
[elem for elem in mylist if elem.strip()]
- Joachim Isaksson>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> filter(str.strip, mylist)
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> list(filter(str.strip, mylist))
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
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']
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']
>>>
mylist = [x for x in [ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"] if x]
使用“if”子句的列表推导,而在这种情况下,依赖于Python在布尔上下文中将空字符串(和空容器)视为“False”的事实。
如果您所说的“空”是指长度为零或仅包含空格,则可以将if
子句更改为if x.strip()
>>> 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']
mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
mylist = [word for word in mylist if word.isalpha()]
print mylist
Output:['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
mylist = [s for s in mylist if str is not " "]
list = ["first", "", "second"]
[x for x in list if x]
输出:['第一个','第二个']
根据建议缩短,下面给出相同的问题
>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> [i for i in mylist if i.strip() != '']
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
[elem for elem in mylist if not elem.isspace()]
- Sukrit Kalra