lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

    • Python 基础

    • Python 数据库

    • 面向对象

    • Python Web

    • Python 进阶

      • 协程
      • 装饰器
      • decorator
      • filter
        • filter
      • 列表生成式
      • 进程&线程
      • 生成器
      • 匿名函数
      • map&&reduce
      • venv
  • leetcode

  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • python
  • 进阶
2024-06-09
目录

filter

# filter

跟 map()类似,接收函数和可迭代对象
不同的是 filter通过函数返回的值是 True 或者 False来决定是否抛弃这个元素。

## 只保留奇数
def is_odd(n):
    return n % 2 != 0


print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))
## 去掉序列中的空元素,包括 None, 空字符串,只包含空格字符
def not_empty(str):
    ## 前者去掉 None, '', 后者去掉 '   '
    return str and str.strip()


print(list(filter(not_empty, ['A', '', 'B', None, 'C', '  '])))

# 测试

## 回数
def is_palindrome(n):
    res = 0
    tmp = n
    while tmp != 0:
        last_digit = tmp % 10
        res = res * 10 + last_digit
        tmp = tmp // 10
    return res == n


output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:
    print('测试成功!')
else:
    print('测试失败!')

decorator
列表生成式

← decorator 列表生成式→

最近更新
01
lhl learn notes
02
decorator
06-09
03
商业价值理解
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式