简体   繁体   English

无法理解lambda地图功能

[英]unable to understand lambda map function

Seeking guidance to understand a lambda-map function. 寻求指导以了解lambda-map函数。 In the below, I see that the file "feedback" is read line by line and stored in a list "feedback". 在下面,我看到文件“ feedback”逐行读取并存储在列表“ feedback”中。 I'm unable to get my head around the variable x. 我无法理解变量x。 I don't see the variable "x" declared anywhere. 我在任何地方都看不到变量“ x”。 Can someone help me understand the statement?Thanks in advance 有人可以帮助我理解该声明吗?

f = open('feedback.txt','r') 
feedback = list(map(lambda x:x[:-1],f.readlines())
f.close()

The map function will execute the given function for every element in the list. map函数将为列表中的每个元素执行给定的函数。

In your code the map function will get lambda x:x[:-1] . 在您的代码中,map函数将获得lambda x:x[:-1] You can read that like: for every x in f.readlines() return everything except the last element of x. 您可以像这样读取:对于f.readlines()中的每个x,返回除x的最后一个元素以外的所有内容。

So x will be every line the file. 因此x将是文件的每一行。 lambda x: you could see as def thing(x): . lambda x:您可以将其视为def thing(x):

I replaced lambda with a standard func: 我用标准功能替换了lambda:

def read_last(x):  #x means a line
  return x[:-1]

f = open('feedback.txt','r') 
feedback = list(map(read_last, f.readlines())
f.close()

Maybe it will help. 也许会有所帮助。

lambda function is a simple anonymous function that takes any number of arguments, but has only one expression. lambda函数是一个简单的匿名函数,它可以接受任意数量的参数,但是只有一个表达式。

lambda arguments : expression

It is anonymous because we have not assigned it to an object, and thus it has no name. 它是匿名的,因为我们尚未将其分配给对象,因此它没有名称。

example f and g are somewhat same: 示例f和g有点相同:

def f(x):
    # take a string and return all but last value
    return x[:-1]

g = lambda x: x[:-1]

so: 所以:

f('hello') == g('hello') #True ->'hell'

But g is not how we would use lambda. 但是g并不是我们使用lambda的方式。 The whole aim is to avoid assigning ;) 整个目的是避免分配;)

Now map takes in a function and applies it to an iteratable:it returns a generator in Python 3+ and thus a list is used to case that generator to a list 现在map接受一个函数并将其应用于iteratable:它在Python 3+中返回一个生成器,因此使用了一个列表将该生成器的大小写转换为一个列表

data = ['we are 101','you are 102','they are 103']

print(list(map(lambda x:x[:-1],data)))

#->['we are 10','you are 10','they are 10']

In principle, same as passing a function: 原则上,与传递函数相同:

data = ['we are 101','you are 102','they are 103']

print(list(map(f,data)))

but often faster and awesome. 但通常更快又很棒。 I love lambdas 我爱lambdas

Keep in mind, while explaining lambda is solved here, it is not the implementation of choice for your particular example. 请记住,在这里解释lambda时已解决,但这不是您的特定示例选择的实现。 Suggestion: 建议:

f = open('feedback.txt', 'r')
feedback = f.read().splitlines()
f.close()

See also 'Reading a file without newlines'. 另请参阅“读取没有换行符的文件”。

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

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