我想从Python的字符串列表中删除所有空字符串。
我的想法看起来像这样:
我的想法看起来像这样:
while '' in str_list:
str_list.remove('')
有没有更符合 Python 风格的方法来完成这个任务?
请记住,如果您想保留字符串内的空格,使用某些方法可能会无意中将它们删除。
如果您有如下列表:
['hello world', ' ', '', 'hello']
您可能需要的是 ['hello world','hello']
首先,修整列表以将任何类型的空格转换为空字符串:
space_to_empty = [x.strip() for x in _text_list]
space_clean_list = [x for x in space_to_empty if x]
space_clean_list = [x.strip() for x in y if x.strip()]
。 - Muhammad Mehran Khan Attarifilter
:newlist=filter(lambda x: len(x)>0, oldlist)
# I am assuming listtext is the original list containing (possibly) empty items
for item in listtext:
if item:
newlist.append(str(item))
# You can remove str() based on the content of your original list
这是最直观的方法之一,执行速度也不错。
lambda x: len(x)
还糟糕,而后者比lambda x : x
还差,而这四个解决方案中最差的是被选中的答案。虽然正确的功能是首选,但并不足够。将光标悬停在“踩”按钮上:它会显示“This answer is not useful”。 - John Machinlstr = ['hello', '', ' ', 'world', ' ']
r=re.compile('^[A-Za-z0-9]+')
results=list(filter(r.match,lstr))
print(results)
for x in list
迭代列表时,您永远不应该修改该列表。如果您使用while loop
,则可以这样做。演示的循环将删除空字符串,直到没有更多的空字符串为止,然后停止。实际上,我甚至没有看问题(只看了标题),但我给出了完全相同的循环作为可能性!如果您不想出于内存考虑使用 comprehensions 或 filters,则这是一种非常 Pythonic 的解决方案。 - aaronasterlingfor var in list:
的形式,那么他会进行遍历。但是在这里,他写成了while const in list:
的形式。这并不是在遍历任何内容,它只是在满足条件为假之前一直重复相同的代码。 - Camiondata = list(filter(None, str_list))
- Jacob Ward