python 高阶函数:filter(过滤器)
admin
2023-07-24 01:22:20
0

官网解释:

  • filter(functioniterable)

  • Construct a list 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 iterable is a string or a tuple, the result also has that type; otherwise it is always a list. 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 [item for item in iterable if function(item)] if function is not None and [item for itemin iterable if item] if function is None.

    See itertools.ifilter() and itertools.ifilterfalse() for iterator versions of this function, including a variation that filters for elements where the function returns false.



  • str.strip([chars])

  • Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

    >>> '   spacious   '.strip()
    'spacious'
    >>> 'www.example.com'.strip('cmowz.')
    'example'

就是,如果省略参数,默认过滤空格。


#过滤list中的偶数

def get_odd(s):
    return s % 2 == 1;   #C语言绝对不能这么写
   
print "get odd:", filter(get_odd, [1, 2, 3, 4, 5, 6])

python 高阶函数:filter(过滤器)


#过滤list中的空格

def not_empty(s):
    return s and s.strip()   #s过滤了'None'元素,s.strip()默认过滤空格
   
print "not_empty:", filter(not_empty, ['A', ' ', 'B', None, 'C', '  '])

python 高阶函数:filter(过滤器)



补充:

.strip(None/string):从头尾开始,按对象字符串顺序删除

a.如果strip参数中没有对象头尾开始的字符,则无法删除,返回对象全字符

str1 = 'www.example.com'
print (str1.strip('lcoz.'))

  ####strip参数中没有'w'/'m',两端删除受阻


b.如果strip参数中有对象的头尾开始字符,则匹配删除参数中的字符,返回未删除字符

str1 = 'www.example.com'
print (str1.strip('lcwmeoza.'))

xamp   ####strip参数中没有'x'/'p',两端删除受阻







相关内容

热门资讯

对话小湃科技 | 家庭智能体3... 近日,深圳小湃科技有限公司以“破界新生 AI护万家”为主题召开品牌战略升级大会,“小湃有钳”Claw...
委内瑞拉不到一天已发生138次... 新华社加拉加斯6月25日电(记者田睿 许咏政)委内瑞拉全国代表大会主席豪尔赫·罗德里格斯25日表示,...
2026年财富中国科技50强出... 【CNMO科技消息】近日,CNMO科技注意到,2026年财富中国科技50强出炉,华为投资控股有限公司...
2026中国移动“牵手计划”全... 6月25日,在2026上海世界移动通信大会期间,中国移动成功举办“牵手计划”(hi-H Progra...
厦钨新能获得实用新型专利授权:... 证券之星消息,根据天眼查APP数据显示厦钨新能(688778)新获得一项实用新型专利授权,专利名为“...
2026年大学生AI影像旗舰手... OPPO数码全家桶 随着2026年高考结束,准大学生们即将开启新的人生篇章,一款功能强大、体验出色的...
原创 为... 文昌航天发射场的301号工位上,一道烈焰划破长空。 2月11日11时00分,长征十号运载火箭点火升空...
共筑健康驿站新生态 第六届星辰... 2026年6月15日至18日,第六届医药流通贸易大会暨第六届医药零售业大会(简称“第六届星辰会”)在...
一个智谱,相当于半个阿里巴巴? “年亏损47亿的智谱,市值跻身万亿港元阵营。 “这个估值能睡得着觉吗?”对于智谱的市值,不少市场人士...
原创 小... 小米新机量越来越多,比如小米17T系列、REDMI K90至尊版等,可谓是新机连连。其中小米17全系...