Blogger Information
Blog 41
fans 0
comment 1
visits 40475
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Python高效编程技巧实战(1)
yeyiluLAMP
Original
797 people have browsed it

开发环境:以Python2.x为主

第一天 : 01day

如何在列表、字典、集合中根据条件筛选数据
实际案列:过滤掉列表[3,9,-1,10,20,-2...]
模拟环境:创建-10~10之间的整数
from random import randint
data = [randint(-10,10) for _ in xrange(10)]
通用的方法:
res = []
for x in data:
    if x >=0:
        res.append(x)
print res


匿名函数的方法:
filter(lambda x:x >= 0,data)

列表生成式的方法:
[x for x in data if x >= 0]

筛选字典{'LiLei':79,'Jim':88,'Lucy':92...}中值高于90的项
模拟环境:某班有20名学生,筛选出成绩90分以上(含90)的学生成绩
d = {x:randint(60,100) for x in xrange(1,21)}
{k:v for k,v in d.iteritems() if v >= 90}

筛选集合{77,89,32,20...}中能被3整除的元素
模拟环境:列表data变成一个集合s,并且筛选出能被3整除的元素的集合
s = set(data)
{x for x in data if x % 3 == 0}








Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post