简体   繁体   English

在python中有一个列表,使用lambda和map / filter生成新列表

[英]having a list in python,using lambda and map/filter to generate new list

i have a list: 我有一个清单:

seq = ['soup','dog','salad','cat','great']

As per the definition of filter, below code fetches the correct result: 根据过滤器的定义,以下代码可获取正确的结果:

list(filter(lambda w: w[0]=='s',seq))

['soup','salad']

ie returning the list containing only words starting with 's' 即返回仅包含以's'开头的单词的列表

but if i am using map function, it is returning the list as true/false: 但是,如果我使用的是map函数,它将以true / false的形式返回列表:

list(map(lambda w: w[0]=='s',seq))`

[True, False, True, False, False]

please explain the map function wrt to the above example 请向上面的示例解释map函数wrt

map applies a function to a sequence and returns a generator. map将函数应用于序列并返回生成器。

Example: 例:

k = list(map(int,["1","2","3"]))

int() is a function string->int hence k becomes: int()是函数string->int因此k变为:

k ==  [1,2,3] # (a list of ints)

Your lambda is a fuction string->bool that takes a string and evaluates the first char to be 's' or not: 您的lambda是一个函数string->bool ,它接受一个string并计算第一个字符是否为's'

lambda w: w[0]=='s'

As a function of string->bool , your result is a list of bool s when using list(map(lambda w: w[0]=='s', seq)) to apply your lambda to your sequence. 作为的函数的string->bool ,你的结果是一个listbool使用当s list(map(lambda w: w[0]=='s', seq))到您的拉姆达应用到您的序列。


Btw. 顺便说一句。 you could also have done it as list comprehension: 您也可以将其作为列表理解:

s_seq = [x for x in seq if x[0]=='s'] # which is closer to what filter does...

This might shed more light on map() : Understanding the map function 这可能会更了解 map()了解地图功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM