Python函式之filter 和strip

2021-10-19 08:12:42 字數 1392 閱讀 9672

python函式之filter()和strip()

"

編寫乙個remove_false 函式 將引數中的"假"去掉

remove_false([0, 1, 2, false, '', "fishc", 34])

[1, 2, 'fishc', 34]

"""lst = [0, 1, 2, false, '', "fishc", 34]

def remove_false(lst):

return list(filter(bool, lst))

print(remove_false(lst))

"""

總結:filter函式描述:用於過濾序列,過濾不符合條件的元素,返回符合條件的新列表

接受兩個引數,第乙個為函式,第二個為序列,序列的每元素作為引數傳遞,將true的元素放到新列表

語法:filter(function, iterable)

引數:function 判斷函式

iterable 可迭代物件

返回值:

列表「」"

def is_odd(n):

return n % 2 == 1

print(list (filter(is_odd,[1,2,3,4,5,6,7,8,9])))

執行結果:[1, 3, 5, 7, 9]

def not_empty(s):

return s and s.strip()

print(list(filter(not_empty, ['a', '', 'b', none, 'c',' '])))

"""

補充知識點:strip函式

描述:用於移除字串頭尾指定的字元,預設不填刪除空格和換行符(\n\r\t\ ,』』)

注意:只能去掉開頭和結尾的指定字元

語法:str.strip([chars])

引數:chars—移除字串頭尾指定字元 (只要是邊上的字元就刪掉)

返回:生成新的字串

「」"

****

1預設不填引數

a = '   123'

a.strip()

結果:123
b = '\t\tabc'

b.strip()

結果:abc
新增引數chars,只要邊(開頭或結尾)上的字元在刪除序列內,就刪除掉。

a = '123jdd'

a.strip('21')

結果:『3jdd』

python函式之filter函式

例項環境 help filter help on built in function filter in module builtin filter filter function or none,sequence list,tuple,or string return those items of...

python語法之filter 函式

filter 函式是 python 內建的另乙個有用的高階函式,filter 函式接收乙個函式 f 和乙個list,這個函式 f 的作用是對每個元素進行判斷,返回 true或 false,filter 根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list。例如,要從乙個list...

python 內建函式filter

filter 函式是 python 內建的另乙個有用的高階函式,filter 函式接收乙個函式 f 和乙個list,這個函式 f 的作用是對每個元素進行判斷,返回 true或 false,filter 根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list。例如,要從乙個list...