专业编程基础技术教程

网站首页 > 基础教程 正文

python散装笔记——26: 过滤器

ccvgpt 2025-02-11 11:09:16 基础教程 16 ℃


Parameter

Details

python散装笔记——26: 过滤器

function

可调用函数确定条件或无条件,然后使用身份识别函数进行筛选(仅限位置)。

iterable

将被过滤的 iterable(只限位置)

Section 26.1: 过滤器的基本用途

根据某些标准过滤掉序列中的元素:

names = ['Fred', 'Wilma', 'Barney']

def long_name(name):
  return len(name) > 5
filter(long_name, names) # returns a generator
# Out: 

list(filter(long_name, names)) # cast to list
# Out: ['Barney']

(name for name in names if len(name) > 5) # equivalent generator expression
# Out:  at 0x000001C6F49BF4C0>

Section 26.2: 不带函数的过滤器

如果函数参数为 “None”,则将使用标识函数:

list(filter(None, [1, 0, 2, [], '', 'a'])) # discards 0, [] and ''
# Out: [1, 2, 'a']
(i for i in [1, 0, 2, [], '', 'a'] if i) # equivalent generator expression

Section 26.3: 作为短路检查的过滤器

filter(python 3.x)和 ifilter(python 2.x)会返回一个生成器,因此在创建 orand 等短路测试时非常方便:

找出第一个小于 100 的元素:

car_shop = [('Toyota', 1000), ('rectangular tire', 80), ('Porsche', 5000)]
def find_something_smaller_than(name_value_tuple):
  print('Check {0}, {1}$'.format(*name_value_tuple))
  return name_value_tuple[1] < 100
next(filter(find_something_smaller_than, car_shop))

# Print: Check Toyota, 1000$
# Check rectangular tire, 80$
# Out: ('rectangular tire', 80)

next-function 给出了下一个(这里是第一个)元素,因此是短路的原因。

Section 26.4: 互补函数:filterfalse、ifilterfalse

在 itertools 模块中有一个过滤器的补充功能:

from itertools import filterfalse

它的工作原理与生成器过滤器完全相同,但只保留 False 元素:

# Usage without function (None):
list(filterfalse(None, [1, 0, 2, [], '', 'a'])) # discards 1, 2, 'a'
# Out: [0, [], '']
# Usage with function
names = ['Fred', 'Wilma', 'Barney']

def long_name(name):
  return len(name) > 5

list(filterfalse(long_name, names))
# Out: ['Fred', 'Wilma']
# Short-circuit usage with next:
car_shop = [('Toyota', 1000), ('rectangular tire', 80), ('Porsche', 5000)]
def find_something_smaller_than(name_value_tuple):
  print('Check {0}, {1}$'.format(*name_value_tuple))
  return name_value_tuple[1] < 100
next(filterfalse(find_something_smaller_than, car_shop))
# Print: Check Toyota, 1000$
# Out: ('Toyota', 1000)
# Using an equivalent generator:
car_shop = [('Toyota', 1000), ('rectangular tire', 80), ('Porsche', 5000)]
generator = (car for car in car_shop if not car[1] < 100)
next(generator)

Tags:

最近发表
标签列表