官網解釋:
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'
就是,如果省略參數,默認過濾空格。
#過濾list中的偶數
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()默認過濾空格
print "not_empty:", filter(not_empty, ['A', ' ', 'B', None, 'C', ' '])
補充:
.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',兩端刪除受阻
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。