當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python filter()用法及代碼示例


filter()方法借助一個測試序列中每個元素是否為真的函數來過濾給定的序列。

用法:

filter(function, sequence)
參數:
function:function that tests if each element of a 
sequence true or not.
sequence:sequence which needs to be filtered, it can 
be sets, lists, tuples, or containers of any iterators.
返回:
returns an iterator that is already filtered.
# function that filters vowels 
def fun(variable):
    letters = ['a', 'e', 'i', 'o', 'u'] 
    if (variable in letters):
        return True
    else:
        return False
  
  
# sequence 
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r'] 
  
# using filter function 
filtered = filter(fun, sequence) 
  
print('The filtered letters are:') 
for s in filtered:
    print(s)

輸出:


The filtered letters are:
e
e

應用:
通常與Lambda函數一起使用以分隔列表,元組或集合。

# a list contains both even and odd numbers.  
seq = [0, 1, 2, 3, 5, 8, 13] 
  
# result contains odd numbers of the list 
result = filter(lambda x:x % 2, seq) 
print(list(result)) 
  
# result contains even numbers of the list 
result = filter(lambda x:x % 2 == 0, seq) 
print(list(result))

輸出:

[1, 3, 5, 13]
[0, 2, 8]

請參考Python Lambda函數以獲取更多詳細信息。



相關用法


注:本文由純淨天空篩選整理自pawan_asipu大神的英文原創作品 filter() in python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。