简体   繁体   中英

unable to understand lambda map function

Seeking guidance to understand a lambda-map function. In the below, I see that the file "feedback" is read line by line and stored in a list "feedback". I'm unable to get my head around the variable x. I don't see the variable "x" declared anywhere. 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.

In your code the map function will get lambda x:x[:-1] . You can read that like: for every x in f.readlines() return everything except the last element of x.

So x will be every line the file. lambda x: you could see as def thing(x): .

I replaced lambda with a standard func:

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 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:

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. 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

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

Keep in mind, while explaining lambda is solved here, it is not the implementation of choice for your particular example. Suggestion:

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

See also 'Reading a file without newlines'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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