I declare a class Employee
and a list consist of it:
class Employee():
def __init__(self, _name):
self.name = _name
def get_name(self):
return self.name
Tom = Employee("Tom")
Karl = Employee("Karl")
John = Employee("John")
employee_list = [Tom, Karl, John]
Now I want to have a list of their name by applying get_name
in a map:
name_list = map(get_name, employee_list)
Traceback (most recent call last): File "ask.py", line 13, in <module>
name_list = map(get_name, employee_list)
NameError: name 'get_name' is not defined
How could get_name
be not defined?
How do I do to apply member function in a map?
Python map() function is used to apply a function on all the elements of specified iterable and return map object. Python map object is an iterator, so we can iterate over its elements. We can also convert map object to sequence objects such as list, tuple etc.
To get access to the index in the map function:Use the enumerate() function to get an object of index/item tuples. Unpack the index and item values in the function you pass to map() . The function will get passed a tuple containing the index and item on each iteration.
Python map() function map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable. iter : It is a iterable which is to be mapped.
Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.
map(get_name, employee_list)
in your code is equivalent to
[get_name(employee) for employee in employee_list]
not [employee.get_name() for employee in employee_list]
You should declare a get_name
method outside of Employee
class:
def get_name(employee):
return employee.name
or an easier way with Lambda
:
name_list = map(lambda employee: employee.name, employee_list)
You have to call the method from the instance. You can use a lambda for this
name_list = map(lambda e: e.get_name(), employee_list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With