您好,登錄后才能下訂單哦!
官網(wǎng)解釋:
filter
(function, iterable)
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'
就是,如果省略參數(shù),默認(rèn)過濾空格。
#過濾list中的偶數(shù)
def get_odd(s):
return s % 2 == 1; #C語言絕對不能這么寫
print "get odd:", filter(get_odd, [1, 2, 3, 4, 5, 6])
#過濾list中的空格
def not_empty(s):
return s and s.strip() #s過濾了'None'元素,s.strip()默認(rèn)過濾空格
print "not_empty:", filter(not_empty, ['A', ' ', 'B', None, 'C', ' '])
補(bǔ)充:
.strip(None/string):從頭尾開始,按對象字符串順序刪除
a.如果strip參數(shù)中沒有對象頭尾開始的字符,則無法刪除,返回對象全字符
str1 = 'www.example.com' print (str1.strip('lcoz.')) ####strip參數(shù)中沒有'w'/'m',兩端刪除受阻
b.如果strip參數(shù)中有對象的頭尾開始字符,則匹配刪除參數(shù)中的字符,返回未刪除字符
str1 = 'www.example.com' print (str1.strip('lcwmeoza.')) xamp ####strip參數(shù)中沒有'x'/'p',兩端刪除受阻
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。