pyDay16
内容来自廖雪峰的官方网站。
1、Python内建的filter()
函数用于过滤序列。
2、和map()
类似,filter()
也接收一个函数和一个序列。和map()
不同的是,filter()
把传入的函数依次作用于每个元素,然后根据返回值是True
还是False
决定保留还是丢弃该元素。
3、例如:过滤出不及格的学生。
>>> def is_fail(n):
... if n < 60 :
... return True
... else:
... return False
...
>>> list(filter(is_fail, [55, 65, 77, 47, 43, 88, 99]))
[55, 47, 43]
注意到filter()
函数返回的是一个Iterator
,也就是一个惰性序列,所以要强迫filter()
完成计算结果,需要用list()
函数获得所有结果并返回list。
4、用fillter求素数
diy版本(按字面意思翻译)
def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
>>> from test import is_prime
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> list(filter(is_prime, [1, 2, 3, 4, 5, 6, 7]))
[2, 3, 5, 7]
5、遇到一个小问题:如果在交互界面漏括号
>>> list(filter(is_prime, list(range(1, 8))))
[2, 3, 5, 7]
>>> list(filter(is_prime, list(range(1, 8)))
...
...
pyDay16的更多相关文章
- py-day1-6 python 5个灰魔法 【len,index索引,for循环,切片】
# 索引,下标,获取字符串中的某一个字符. test = 'MuMingJun' v = test[3] print(v) i # 切片 test = 'MuMingJun' v = test[0:- ...
- PYday16&17-设计模式\选课系统习题
1.设计模式:对程序做整体得规划设计,这样做是为了更好的实现功能,使代码的可扩展性更好有27种常见的设计模式.流行的设计模式参考书:GoF设计模式.大话设计模式设计模式是为了更好的实现模块间的解耦,便 ...
随机推荐
- ring0 根据EThread遍历线程
ntdll!_ETHREAD +0x000 Tcb : _KTHREAD +0x200 CreateTime : _LARGE_INTEGER 0xff58b008 +0x208 ExitTime : ...
- tomcat源码---->request的请求参数分析
当contentType为application/json的时候,在servlet中通过request.getParameter得到的数据为空.今天我们就java的请求,分析一下request得到参数 ...
- 【python系列】python2.x和python3.x的区别
刚接触python使用的是python2.x的书籍,但是发现python3.x和python2.x有不小的区别,以下做一些记录 性能 Py3.0运行 pystone benchmark的速度比Py2. ...
- Eclipse failed to get the required ADT version number from the sdk
failed to get the required ADT version number from the sdk 解决方法: eclipse 和 android studio 工具不能同时共用同一 ...
- Windows Phone 有关独立存储(一)
private const string foldername = "temp1"; private const string filename = foldername + &q ...
- Unity3D笔记六 GUI游戏界面
1.Label:标签控件,可以在游戏中用来展示文本字符串信息,不仅可以写字还可以贴图片. 2.Button:按钮控件,一般分图片按钮和普通的按钮,还有一个连续按钮RepeatButton注意,这个在W ...
- iPad - 开发(Universal Applications)
一.iPad 1.判断是否在iPad上 BOOL iPad = ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdi ...
- 设备信息的管理(Device) ---- HTML5+
模块:Device Device模块管理设备信息,用于获取手机设备的相关信息,如IMEI.IMSI.型号.厂商等.通过plus.device获取设备信息管理对象. 应用场景:打电话,铃声提醒,震动提醒 ...
- PHP中文字数限制:中文字符串截取(mb_substr)
一.中文截取:mb_substr() mb_substr( $str, $start, $length, $encoding ) $str,需要截断的字符串 $start,截断开始处,起始处为0 $l ...
- mysql数据库多源复制方案
概述 由于目前生产环境的mysql数据库分布在两台服务器,若从单一主从来看,配置很简单,但是需要将两台服务器的数据库同步到一台从库上面,需要进行更多配置和注意事项.多源复制有两种方案,Binlog+P ...