如何简化删除列表中空白字符串的方法?

2024-04-20 05:46:50 发布

您现在位置:Python中文网/ 问答频道 /正文

x=["x1",""," ","   ","y1"]
y=[]
import re
for id in range(0,5):
    if(not re.findall("^\s*$",x[id])): y.append(x[id])

y
["x1","y1"]

我可以在python中删除列表中的空白字符串,感觉很复杂,如何简化代码?你知道吗


Tags: 字符串inimportreid列表forif
3条回答
y = filter(lambda i: i.strip(), x)
#['x1', 'y1']

或更简洁的版本@Jiri

filter(str.strip, x)

您可以使用基于列表理解的过滤,如下所示

print [current_string for current_string in x if current_string.strip() != ""]
# ['x1', 'y1']

在Python中,an empty string is considered as Falsy。所以,也可以这样简洁地写

print [current_string for current_string in x if current_string.strip()]

除此之外,您还可以使用^{}函数,像这样过滤掉空字符串

stripper, x = str.strip, ["x1",""," ","   ","y1"]
print filter(stripper, x)

list comprehension带if语句:

y = [i for i in x if i.strip()]
#['x1', 'y1']

相关问题 更多 >