Python魔法_筛选符合条件的值

本文探讨了在Python中如何筛选列表、字典和集合中符合条件的元素,对比了列表解析和filter函数的效率,指出列表解析通常比filter函数更快。同时介绍了相关数据结构的创建及解析方法。

列表:
- 筛选列表中符合条件的元素
最常用的是迭代法,常用的有列表解析和filter函数过滤。 但是filter函数过滤的消耗时长要大于列表解析

  • 创建列表
from random import randint
    data = [randint(-10 ,10) for _ in range(10)]
  • 进行过滤处理:
print (filter(lambda x:x>=0,data))

OR

  • 列表解析
[ x for x in data if x >=0 ] 
即:for x in data ,if x>=0 ,return x 

字典:

  • 创建字典
d = [ x:randint(60,100) for x in range(1,21)]
  • 字典解析
print ({k:v for k,v in d.iteritems() if v >=90})

集合:

  • 创建集合
s = set(data)
  • 集合解析:
print ({ x for x in s if x%3==0 })
  • 对相关函数的解释:
filter(...)
    filter(function or None, sequence) -> list, tuple, or string

    Return those items of sequence for which function(item) is true.  If
    function is None, return the items that are true.  If sequence is a tuple
    or string, return the same type, else return a list.
    接受一个函数和一个列表,返回一个列表
lambda 函数:操作
匿名函数,和函数的功能是一样的,传入参数,进行操作
randint(self, a, b)
    Return random integer in range [a, b], including both end points. 
iteritems(...)
 |      D.iteritems() -> an iterator over the (key, value) items of D
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值