Python 字典列表筛选数据

有时候人只需要一只温暖的手的触摸,就像是拥有了整个世界。我一直在等,等到绝望。
import sys
import random
reload(sys)
sys.setdefaultencoding('utf-8')

生成列表

data_list=[random.randint(1,100) for _ in range(10)]
//randint是在数值中随机选择一个,从1-100选择10个数字

生成字典

data_dict={k:random.randint(60,100) for k in range(1,21)}
//字典格式是键:值。键为1-20,值为60-100

使用Filter筛选

print filter(lambda x:x>60,data_list)
//匿名函数lamba,常常搭配map,reduce,filter使用
//map返回的是新的对象,filter就是符合条件的就返回,reduce就是遍历循环

使用列表推导

print [x for x in data_list if x>60]
//列表推导,并做判断,其实很好理解

字典筛选

print {k:v for k,v in data_dict.iteritems() if v>5}
如果直接遍历字典的话,就是遍历字典的键
可以试一试`for x in data_dict:printx`
如果想要同时循环键与值的话,就用`for k,v in data_dict.iteritems():print k,v`
坚持原创技术分享,您的支持将鼓励我继续创作!

-------------本文结束感谢您的阅读-------------

腾讯云主机优惠打折:最新活动地址


版权声明

LangZi_Blog's by Jy Xie is licensed under a Creative Commons BY-NC-ND 4.0 International License
由浪子LangZi创作并维护的Langzi_Blog's博客采用创作共用保留署名-非商业-禁止演绎4.0国际许可证
本文首发于Langzi_Blog's 博客( http://langzi.fun ),版权所有,侵权必究。

0%