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

时间:2014-03-15 09:19:36

标签: python list

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列表中的空白字符串,感觉很复杂,我怎样才能简化代码?

4 个答案:

答案 0 :(得分:2)

使用if语句

list comprehension

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

答案 1 :(得分:2)

y = filter(lambda i: i.strip(), x)
#['x1', 'y1']
@Jiri

或更简洁的版本
filter(str.strip, x)

答案 2 :(得分:0)

>>> o = ['','1']
>>> n = []
>>> for each in o:
     if each.strip():
        n.append(each)
>>> n
['1']
>>> 

答案 3 :(得分:0)

你可以使用基于列表理解的过滤,就像这样

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()]

除此之外,您可以使用filter函数来过滤掉这样的空字符串

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