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 返回迭代器對象
