栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python filter 函数

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python filter 函数

filter 可以用于过滤列表,返回一个新的 iterator 对象。
以下是一个数组,找出其中的奇数:

nums = [5, 10, 23, 64, 42, 53, 93, 2, 0, -14, 6, -22, -13]

def check_odd(x):
    if x % 2:
        return True
    else:
        return False

odds_func = filter(check_odd, nums)
print(list(odds_func))
# [5, 23, 53, 93, -13]

filter 的第一个参数可以改成 lambda 函数:

nums = [5, 10, 23, 64, 42, 53, 93, 2, 0, -14, 6, -22, -13]

odds = filter(lambda x: x % 2, nums)
print(list(odds))
# [5, 23, 53, 93, -13]

evens = filter(lambda x: not (x % 2), nums)
print(list(evens))
# [10, 64, 42, 2, 0, -14, 6, -22]

除了 filter 函数之外, 也可以使用 list comprehension 找出列表中的奇偶数:

nums = [5, 10, 23, 64, 42, 53, 93, 2, 0, -14, 6, -22, -13]

print("odds: ", [x for x in nums if x % 2])
# odds:  [5, 23, 53, 93, -13]

print("evens: ", [x for x in nums if not (x % 2)])
# evens:  [10, 64, 42, 2, 0, -14, 6, -22]
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/997788.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号