Python示例中的Lambda和filter

先决条件: Python中的Lambda

null

给出一个数字列表,找出所有可被13整除的数字。

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

我们可以使用 拉姆达 函数,以查找列表中可被13整除的所有数字。在Python中,匿名函数意味着函数没有名字。

Python中的filter()函数接受函数和列表作为参数。这提供了一种优雅的方法,可以过滤掉序列“sequence”中的所有元素,函数将为其返回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
result = list ( filter ( lambda x: (x = = "".join( reversed (x))), my_list))
# printing the result
print (result)


输出:

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

给定字符串列表和字符串str,打印str的所有字谜

# 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
result = list ( filter ( lambda x: (Counter( str ) = = Counter(x)), my_list))
# printing the result
print (result)


输出:

['geeks', 'keegs']
© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享