在Python中使用filter函数来移除列表中所有空字符串
发布时间:2023-07-01 10:43:26
在Python中,我们可以使用filter函数来过滤列表中的元素。filter函数接受两个参数, 个参数是一个函数,第二个参数是一个可迭代对象(如列表),并返回一个过滤后的可迭代对象。
首先,我们需要定义一个函数来判断字符串是否为空。可以使用字符串的strip()方法来去除字符串前后的空格,然后使用bool()函数来判断去除空格后的字符串是否为空。如果字符串为空,则返回False,否则返回True。函数定义如下:
def not_empty(string):
return bool(string.strip())
然后,我们可以使用filter函数来移除列表中的空字符串。将列表和函数传递给filter函数,并将其结果转换为列表。代码如下:
my_list = ['apple', '', 'banana', 'orange', '', 'grape'] filtered_list = list(filter(not_empty, my_list)) print(filtered_list)
运行以上代码,输出结果为['apple', 'banana', 'orange', 'grape'],即移除了列表中的空字符串。
完整代码如下:
def not_empty(string):
return bool(string.strip())
my_list = ['apple', '', 'banana', 'orange', '', 'grape']
filtered_list = list(filter(not_empty, my_list))
print(filtered_list)
这样,我们就成功使用filter函数来移除列表中的所有空字符串。
