Get equivalent expression to list(zip(list, Heights)) using the map() function

Asked

Viewed 95 times

5

Be:

heights = [x*0.0254 for x in [69,77,54]]
lista = [69,77,54]

The expression:

print(list(zip(lista,heights)))

has as output:

[(69, 1.7526), (77, 1.9558), (54, 1.3716)]

My goal is to get the same output but using the function map():

I tried to make:

print(list(map(lambda x,y:zip(x,y),lista,heights)))

but I’m getting the bug:

print(list(map(lambda x,y:zip(x,y),lista,heights)))
TypeError: 'int' object is not iterable

What am I doing wrong? How to correct the expression using map() in order to obtain the same output below?

[(69, 1.7526), (77, 1.9558), (54, 1.3716)]

1 answer

4


The mistake is in the zip(x,y). What the function zip() makes is, for each element of the list x , joins with the corresponding element at the position of the list y in a tuple and adds it to a list. That is, this function waits as parameters eternal objects, as lists by exeplo.

The function map() executes a function specified for each item in an iterable. The item is sent to the function as a parameter.

In practice, what you are doing is passing to your function zip() the values 69 and 1.7526, that are not eternal, for being whole and float. That’s why the error appears:

Typeerror: 'int' Object is not iterable

That is, an object of the type int is not eternal.

Breaking the problem by pieces, we have:

def myFunc(x,y):
  return (x,y) 

>>> print(list(map(myFunc, [69,77,54], [1.7526, 1.9558, 1.3716])))
    [(69, 1.7526), (77, 1.9558), (54, 1.3716)]

The idea of using the lambda is that it enters as the function, so instead of declaring a function myFunc, can use direct lambda x,y: (x,y):

>>> print(list(map(lambda x,y: (x,y), [69,77,54], [1.7526, 1.9558, 1.3716])))
    [(69, 1.7526), (77, 1.9558), (54, 1.3716)]

But it is also possible to leave even more automatic:

print(list(map(lambda x: (x, x*0.0254),[69,77,54])))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.