鱼C论坛

 找回密码
 立即注册
查看: 2636|回复: 4

[已解决](小白)小甲鱼老师课堂上这段代码理解不了求教

[复制链接]
发表于 2016-12-30 14:11:04 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
求教部分见课堂视频截图。

def odd(x):
       return  x%2

如果让 range(10)的 0,1,2,3,4,5,6,7,8,9  依次代入odd这个函数

那么结果应该是:0,1,0,1,0,1,0,1,0,1

为什么 fliter(odd,range(10))中的odd 就代表0,最终踢掉所有的偶数呢?

为啥odd不能代表1,踢掉所有的奇数呢?

最佳答案
2016-12-30 15:26:39
filter(function, iterable)
Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.


以后遇到问题了,先按F1 看说明文档,一般小的问题,看了以后都能明白
第一句说的就很明白了
Construct an iterator from those elements of iterable for which function returns true.

这个函数会滤掉所有函数值返回为true的值
你这个程序里面,odd函数输入为奇数的时候,返回1,(所有非零数字都判定为true),所以所有的奇数就都过滤掉了
你如果想要得到奇数序列,那就把odd函数改成 return x%2-1就可以了
打打杀杀的.JPG
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-12-30 15:04:07 | 显示全部楼层
在python中0为False,非0为True。filter就是过滤掉False的值。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-12-30 15:26:39 | 显示全部楼层    本楼为最佳答案   
filter(function, iterable)
Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.


以后遇到问题了,先按F1 看说明文档,一般小的问题,看了以后都能明白
第一句说的就很明白了
Construct an iterator from those elements of iterable for which function returns true.

这个函数会滤掉所有函数值返回为true的值
你这个程序里面,odd函数输入为奇数的时候,返回1,(所有非零数字都判定为true),所以所有的奇数就都过滤掉了
你如果想要得到奇数序列,那就把odd函数改成 return x%2-1就可以了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-12-30 15:28:02 | 显示全部楼层
还有以后代码用代码格式发出来,在编辑栏有个<>符号,把代码粘进去就可以了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-12-30 15:39:30 | 显示全部楼层
哦 明白了 谢谢解惑的大牛
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-13 03:19

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表