程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Learn the filter() function in Python

編輯:Python

Python filter() 函數是另一個[內置]函數,Helpful when working with data.filter() Except that the function accepts a sequence as input,Actually also accepts a function as input,and returns an iterator constructed from the items in the given sequence,對於這些項目,The given function returns true.If you want to collect everything in the result at the same time,你可以對filterThe resulting iterator call[list()]函數.


使用Lambda的filter()

We recently learned[Python 中的 lambda 函數],They are discussed with us herefilter()It is very common to use functions together.讓我們看一個實際的例子,Look at a list of numbers,Only even numbers are filtered out.

# Python Program to find even numbers
# from a list using an anonymous function
# Take a list of numbers.
list_of_ints = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# use anonymous lambda function to filter
result = list(filter(lambda x: (x % 2 == 0), list_of_ints))
# printing the result
print(result)
復制代碼
[2, 4, 6, 8]
復制代碼

過濾器和lambda的例子二

The next example is to look at a list of strings.Some of these strings are palindromes.This means their reverse spelling is the same as normal.我們可以使用filter()和lambda函數,Only palindromes in the list are found.

# Python Program to find palindromes in a list of strings.
list_of_strings = ['ferrari', 'racecar', 'tesla', 'level', 'technoking']
# use an anonymous function to filter palindromes.
result = list(filter(lambda x: (x == ''.join(reversed(x))), list_of_strings))
# print the palindromes
print(result)
復制代碼
['racecar', 'level']
復制代碼

使用filter()的自定義函數

我們也可以使用 Python 中的標准defkeyword to define a named function,Then combine this named function with filter() 函數結合使用.Here we will create a function that can filter odd numbers from a list.

# list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
# function that finds odd numbers
def is_odd(num):
if (num % 2) != 0:
return True
else:
return False
results = filter(is_odd, numbers)
print(list(results))
復制代碼
[1, 3, 5, 7, 9, 11]
復制代碼

使用 filter() 刪除重復的數字

meats1 = ['steak', 'chicken', 'pork', 'bacon', 'ground beef']
meats2 = ['sausage', 'pork', 'duck', 'lamb', 'steak']
# function that filters duplicate string
def filterDuplicate(string_to_check):
if string_to_check in the_list:
return False
else:
return True
# Using filter() to remove duplicate strings
the_list = meats2
results = list(filter(filterDuplicate, meats1))
the_list = meats1
results += list(filter(filterDuplicate, meats2))
print("Duplicates removed: ", results)
復制代碼
Duplicates removed: ['chicken', 'bacon', 'ground beef', 'sausage', 'duck', 'lamb']
復制代碼

filter()check for truth

要理解 filter() A key concept of functions is ,It's checking for one True 條件.Only true values ​​pass the filter.我們可以通過將Python的NoneThe value is passed to as a functionfilter()來證明這一點,The function will still work.Let's look at the concept here.

# list of values
list_of_values = ['1', 2, 0, False, True, '1', [], {}]
filtered_list = filter(None, list_of_values)
print('The filtered elements are:')
for element in filtered_list:
print(element)
復制代碼
The filtered elements are:
1
2
True
1
復制代碼

在 Dict 中使用 filter()

到目前為止,We've seen how some are used in various lists filter() 的例子.我們還可以在 Python used for dictionaries filter() 函數.

dictOfNames = {
0: 'Rick',
1: 'Vick',
2: 'Bob',
3: 'Rob',
4: 'Soham',
5: 'Dave'
}
# Filter dictionary by keeping elements whose values contain
# the letter 'a'
newDict = dict(filter(lambda elem: 'a' in elem[1], dictOfNames.items()))
print('Filtered Dictionary : ')
print(newDict)
復制代碼
Filtered Dictionary :
{4: 'Soham', 5: 'Dave'}
復制代碼

Python filter() 函數總結

filter() The function constructs an iterator from the elements of an iterator,for this iterator,一個函數返回 true.其工作方式是 filter() Method filters the given iterator with the help of a function,This function tests whether each element in the iterator is true.

filter()函數的語法如下:

filter(function, iterable)

filter()的參數是functioniterable.

  • function- A function that tests whether an element in an iterator returns true or false
    如果沒有,函數默認為Identity函數 - False if there are elements,則返回假
  • iterable- Iterator to be filtered,可以是集合、列表、A container for primitives or any iterator.

filter()函數返回一個迭代器,The iterator passes the function check for each element in the iterator.

使用lambda時,filter()函數的語法如下:

filter(lambda item: item[] expression, iterable)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved