2018-03-26 18:45:52 789浏览
filter函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。filter函数接收一个函数func和一个iterable(可以是list,字符串等),这个函数func的作用是对每个元素进行判断,返回True或False,filter根据判断结果自动过滤掉不符合条件的元素,最后将返回True的元素放到新列表中。
Constructaniteratorfromthoseelementsofiterableforwhichfunctionreturnstrue.iterablemaybeeitherasequence,acontainerwhichsupportsiteration,oraniterator.IffunctionisNone,theidentityfunctionisassumed,thatis,allelementsofiterablethatarefalseareremoved. Notethatfilter(function,iterable)isequivalenttothegeneratorexpression(itemforiteminiterableiffunction(item))iffunctionisnotNoneand(itemforiteminiterableifitem)iffunctionisNone.
#!/usr/bin/python #-*-coding:UTF-8-*- list=[1,2,4,6,8,9] defis_gt_5(num): returnnum>5 new_list=filter(is_gt_5,list) print(new_list)
1[6,8,9]
>>>name='pythontab.com2018' >>>filter(str.isdigit,name) '2018'
>>>filter(str.isalpha,name) 'pythontabcom'
>>>filter(lambdachar:charin‘0123456789.’,name) '.2018'
最后想要了解更多关于Python发展前景趋势,请关注扣丁学堂python培训官网、微信等平台,扣丁学堂IT职业在线学习教育平台为您提供最新的Python视频教程系统,通过千锋扣丁学堂金牌讲师在线录制的Python视频教程课程,让你快速掌握Python从入门到精通开发实战技能。扣丁学堂Python开发工程师技术交流群:279521237。
【关注微信公众号获取更多学习资料】