Python示例中的Lambda和filter用法指南

2021年3月10日16:00:11 发表评论 902 次浏览

``````Input : my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70]
Output : [65, 39, 221]``````

Python中的filter()函数接受一个函数和一个列表作为参数。这提供了一种精妙的方法来过滤出序列"序列"的所有元素, 为此函数返回True。

``````# Python Program to find numbers divisible
# by thirteen from a list using anonymous
# function

# Take a list of numbers.
my_list = [ 12 , 65 , 54 , 39 , 102 , 339 , 221 , 50 , 70 , ]

# use anonymous function to filter and comparing
# if divisible or not
result = list ( filter ( lambda x: (x % 13 = = 0 ), my_list))

# printing the result
print (result)``````

``[65, 39, 221]``

``````# Python Program to find palindromes in
# a list of strings.

my_list = [ "geeks" , "geeg" , "keek" , "practice" , "aa" ]

# use anonymous function to filter palindromes.
# Please refer below article for details of reversed
# https://www.lsbin.org/reverse-string-python-5-different-ways/
result = list ( filter ( lambda x: (x = = "".join( reversed (x))), my_list))

# printing the result
print (result)``````

``['geeg', 'keek', 'aa']``

``````# Python Program to find all anagrams of str in
# a list of strings.
from collections import Counter

my_list = [ "geeks" , "geeg" , "keegs" , "practice" , "aa" ]
str = "eegsk"

# use anonymous function to filter anagrams of x.
# Please refer below article for details of reversed
# https://www.lsbin.org/anagram-checking-python-collections-counter/
result = list ( filter ( lambda x: (Counter( str ) = = Counter(x)), my_list))

# printing the result
print (result)``````

``['geeks', 'keegs']``