I have a Python map function question.

Asked 2 years ago, Updated 2 years ago, 91 views

The first factor in the map function that's useful in Python is the function The second factor is, I don't know exactly what it means to be a repeatable data type.

And if the return type is a list type, the reason why you put the list in front of you like list(map(functional, itable)) is because What is it?

python map list

2022-09-22 19:03

1 Answers

That's a good question.

So the purpose of a function called map is to run every element of a collection by substituting it with the first factor, the function's factor, and to get the result as a collection.

For example,

numbers = range(1, 11)

def multiply(number):
    return number * 2

list(map(multiply, numbers))
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Numbers can be from 1 to 10.

The map (multiple, numbers) is to repeat the numbers, take out one element by one from the first element to the last element, substitute the multiplicity function factor, and store the results.

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20] is what we make.

In fact, it's good to understand this part when you study functional programming. Functional programming can be said to be an essential element that modern languages (in some way) provide.

It helps a lot in concise logical representation because it makes it easy to deal with ideas as a set.

And to explain why we convert the result of the map to list, Python 2 did not need an explicit conversion because we received the result as list.

The result value was changed to generator when it became python 3.

The reason is to reduce memory usage.

The range function also returned a list in python 2.

On python 2, creating a large list, such as range (0,99999999), could not be created because it would run out of memory.

However, Python 3 returns a generator, so it can be used regardless of memory utilization.

For that reason, the result value of the map also returns generator, not list. Because it is a generator, you use the list to perform all the iterations.

Please understand that generator is the key in Python 3's collection.


2022-09-22 19:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.