1. 程式人生 > >35-Python - 去除list中的空字元

35-Python - 去除list中的空字元

https://www.cnblogs.com/yspass/p/9434366.html

list1 = ['122', '2333', '3444', '', '', None]
a = list(filter(None, list1))  # 只能過濾空字元和None
print(a)  # ['122', '2333', '3444']
 
 
# Python內建filter()函式 - 過濾list
# filter()把傳入的函式依次作用於每個元素,然後根據返回值是True還是False決定保留還是丟棄該元素
def not_empty(s):
    return s and s.strip()
 
list2 = ['122', '2333', '3444', ' ', '422', ' ', '    ', '54', ' ', '', None, '   ']
print(list(filter(not_empty, list2)))  # ['122', '2333', '3444', '422', '54']
# 不僅可以過濾空字元和None而且可以過濾含有空格的字元
注意: Pyhton2.7 返回列表,Python3.x 返回迭代器物件