Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print map object with Python 3? [duplicate]

This is my code

def fahrenheit(T):     return ((float(9)/5)*T + 32)  temp = [0, 22.5, 40,100] F_temps = map(fahrenheit, temp) 

This is mapobject so I tried something like this

for i in F_temps:     print(F_temps)  <map object at 0x7f9aa050ff28> <map object at 0x7f9aa050ff28> <map object at 0x7f9aa050ff28> <map object at 0x7f9aa050ff28> 

I am not sure but I think that my solution was possible with Python 2.7,how to change this with 3.5?

like image 748
MishaVacic Avatar asked Jun 09 '17 15:06

MishaVacic


People also ask

How do you show an object on a map in Python?

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.

How do I extract a map from an object in Python?

Use the Iterable Unpacking Operator * to Convert a Map Object Into a List in Python. In Python, the term unpacking can be defined as an operation whose primary purpose is to assign the iterable with all the values to a List or a Tuple, provided it's done in a single assignment statement.

What is * map 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.

How do I turn a map into a list in Python?

Use the list() class to convert a map object to a list, e.g. new_list = list(map(my_fuc, my_list)) . The list class takes an iterable (such as a map object) as an argument and returns a list object. Copied!


1 Answers

You have to turn the map into a list or tuple first. To do that,

print(list(F_temps)) 

This is because maps are lazily evaluated, meaning the values are only computed on-demand. Let's see an example

def evaluate(x):     print(x)  mymap = map(evaluate, [1,2,3]) # nothing gets printed yet print(mymap) # <map object at 0x106ea0f10>  # calling next evaluates the next value in the map next(mymap) # prints 1 next(mymap) # prints 2 next(mymap) # prints 3 next(mymap) # raises the StopIteration error 

When you use map in a for loop, the loop automatically calls next for you, and treats the StopIteration error as the end of the loop. Calling list(mymap) forces all the map values to be evaluated.

result = list(mymap) # prints 1, 2, 3 

However, since our evaluate function has no return value, result is simply [None, None, None]

like image 156
codelessbugging Avatar answered Sep 22 '22 04:09

codelessbugging