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

来源:互联网 发布:单片机串口啥意思 编辑:程序博客网 时间:2024/05/18 02:17

列表:
- 筛选列表中符合条件的元素
最常用的是迭代法,常用的有列表解析和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
阅读全文
0 0
原创粉丝点击