Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Map calling a function not working

Map not calling the function being passed.

class a:
    def getDateTimeStat(self,datetimeObj):
        print("Hello")

if __name__ == "__main__":
    obj = a()
    print("prog started")
    data = [1,2,3,4,5]
    b = list(map(obj.getDateTimeStat,data))

Expected op on a new line: Hello Hello Hello Hello Hello

Any help will be appreciated....

like image 336
Ankit Solanki Avatar asked Oct 13 '13 05:10

Ankit Solanki


People also ask

How do you use a function on a map?

In React, the map() function is most commonly used for rendering a list of data to the DOM. To use the map() function, attach it to an array you want to iterate over. The map() function expects a callback as the argument and executes it once for each element in the array.

How do you call a map in Python?

The call to map() applies square() to all of the values in numbers and returns an iterator that yields square values. Then you call list() on map() to create a list object containing the square values.

How does map function work in Python?

Map in Python is a function that works as an iterator to return a result after applying a function to every item of an iterable (tuple, lists, etc.). It is used when you want to apply a single transformation function to all the iterable elements. The iterable and function are passed as arguments to the map in Python.

Is map faster than for loop Python?

map() works way faster than for loop. Considering the same code above when run in this ide. Using map():


1 Answers

In Python 3, map values are evaluated lazily. That is, each value is only computed when it's needed. You'll find that regardless of what function you use, it won't get called until you ask for the value of that item in the mapped result, whether by using next() or some other way.

To get what you want, you can do this:

>>> b = map(obj.getDateTimeStat,data)
>>> next(b)
Hello
>>> next(b)
Hello
>>> next(b)
Hello
>>> next(b)
Hello
>>> next(b)
Hello
>>> next(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Or this:

>>> b = list(map(obj.getDateTimeStat,data))
Hello
Hello
Hello
Hello
Hello

Or a variety of other things.

like image 53
pandubear Avatar answered Oct 12 '22 15:10

pandubear