print(list(filter(lambda x: x, list_num)))
结果为:
[1, 2, 3, 8, 3]
栗子2:过滤列表中数字的大小写(针对的是字母全都是大写或小写的情况)
list_word = [‘a’, ‘B’, ‘c’, ‘d’, ‘E’]
print(list(filter(lambda x: x.isupper(), list_word)))
print(list(filter(lambda x: x.islower(), list_word)))
结果为:
[‘B’, ‘E’]
[‘a’, ‘c’, ‘d’]
### 迭代器仅可使用一次的问题
和map一样,filter函数在Python3中返回一个惰性计算的filter对象或迭代器。我们不能通过index访问filter对象的元素,也不能使用len()得到它的长度。
def is_odd(n):
return n % 2 == 1
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)
print(list(newlist))
print(list(newlist))
输出结果为:
<filter object at 0x7fba80a8d630>
[1, 3, 5, 7, 9]
[]
### 规避这个惰性计算的问题,赋值的时候直接用list进行转换一下:
不使用list转换
def is_odd(n):
return n % 2 == 1