我想从python中的字符串列表中删除所有空字符串。
我的想法是这样的:
while '' in str_list:
str_list.remove('')
还有什么更python化的方法吗?
我想从python中的字符串列表中删除所有空字符串。
我的想法是这样的:
while '' in str_list:
str_list.remove('')
还有什么更python化的方法吗?
当前回答
使用过滤器:
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
这是最直观的方法,并在适当的时间。
其他回答
你可以用这样的东西
test_list = [i for i in test_list if i]
其中test_list是要从中删除空元素的列表。
为了消除空字符串,我将使用if x != "而不是if x。是这样的:
str_list = [x for x in str_list if x != '']
这将在列表中保留None数据类型。此外,如果您的列表中有整数,0是其中之一,它也将被保留。
例如,
str_list = [None, '', 0, "Hi", '', "Hello"]
[x for x in str_list if x != '']
[None, 0, "Hi", "Hello"]
使用列表推导式是最python化的方式:
>>> strings = ["first", "", "second"]
>>> [x for x in strings if x]
['first', 'second']
如果列表必须就地修改,因为有其他引用必须看到更新的数据,那么使用slice赋值:
strings[:] = [x for x in strings if x]
使用正则表达式和筛选器进行匹配
lstr = ['hello', '', ' ', 'world', ' ']
r=re.compile('^[A-Za-z0-9]+')
results=list(filter(r.match,lstr))
print(results)
请记住,如果您想在字符串中保留空白,您可能会使用某些方法无意中删除它们。 如果你有这个列表
['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]