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

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

先决条件:Python中的Lambda

给定数字列表, 找到所有可被13整除的数字。

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

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

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']

给定一个字符串列表和一个字符串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
# 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']

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: