当前位置:   article > 正文

python 中的 filter() 函数——用于过滤序列,过滤掉不符合条件的元素,返回符合条件的元素组成新列表。_python filter

python filter

filter()函数的简介和语法:

filter()函数用于过滤序列,过滤掉不符合条件的元素,返回符合条件的元素组成新列表。

filter()语法如下:

filter(function,iterable)

function -- 判断函数。
iterable -- 可迭代对象
  • 1
  • 2
  • 3
  • 4

序列中的每个元素作为参数传递给函数进行判断,
返回True或者False,最后将返回True的元素放到新列表中

filter()用法实例:

筛选出序列中为奇数的元素:

def is_odd(n):
    return n%2 == 1
lst1 = filter(is_odd,[1,2,3,4,5,6,7,8,9,10])
 
# lst = [1,3,5,7,9]
  • 1
  • 2
  • 3
  • 4
  • 5

filter()经常和lambda一起用:

栗子1: 过滤掉列表当中的数字0

list_num = [1, 2, 3, 0, 8, 0, 3]
print(list(filter(lambda x: x, list_num)))

结果为: 
[1, 2, 3, 8, 3]
  • 1
  • 2
  • 3
  • 4
  • 5

栗子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']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

迭代器仅可使用一次的问题

和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]
[]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

规避这个惰性计算的问题,赋值的时候直接用list进行转换一下:

不使用list转换

def is_odd(n):
    return n % 2 == 1

# 不使用list转换 
print("惰性计算")  
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(list(newlist))
for i in newlist:
    print(i,end = " ")
print(list(newlist))
输出结果
惰性计算
[1, 3, 5, 7, 9]
[]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

不使用list转换

def is_odd(n):
    return n % 2 == 1

#不使用list转换 
print("规避惰性计算")
newlist = list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
print(newlist)
for i in newlist:
    print(i,end = " ")
print(newlist)

输出结果:
规避惰性计算
[1, 3, 5, 7, 9]
1 3 5 7 9 [1, 3, 5, 7, 9]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

例子4:与dict构成的列表处理例子

dict_a = [{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}]
test_filter = filter(lambda x : x['name'] == 'python', dict_a)
print(list(test_filter))

输出结果:
[{'name': 'python', 'points': 10}]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号