Why should I use the map function?

Asked 2 years ago, Updated 2 years ago, 16 views

You learned about the map function. But I don't know where to use it, and I don't know what the benefits are. When you define a function, shouldn't you just take the list with the factor?

That is,

def square(my_list):
    result = []
    for num in my_list:
        result.append(num**2)
    return result

I wonder what's the difference between doing this and using a map function to flip through the list.

python

2022-09-21 22:07

3 Answers

I think the way you read and perceive code changes.

 Students = [Chulsu, Younghee, Geumja, Hideo]
Student gender = map (boy or girl, students)

If you look at these codes, you simply understand that student gender is a list that contains the gender of each student in the student list.

A few lines of code that comes out for a statement and one person appends at the same time, if simple, requires a little more cognitive process.

I think the reason why we often use List/Dictionary/Set Compensation instead of for is the same.

There are also performance advantages, but I don't know why or really why.


2022-09-21 22:07

https://bluese05.tistory.com/58 See this for now......the function definition is developer mind. No matter how you define it and how you use it, you just have to implement it as the developer wants. However, using built-in functions or other libraries means using code simply or reliably without errors. The answer to the question is simple. The map() function is so simple that it can be processed with a single line of code


2022-09-21 22:07

Wouldn't you use it because it's possible to express it more neatly and concisely? The list compression is neater than the for statement, and the map is generally neater than the for statement.

// for
a = [1, 2, 3, 4, 5]
for i in range(len(a)):
    a[i] = str(a[i])

a = [1, 2, 3, 4, 5]
// // list comprehensions
a = [str(x) for x in a]

a = [1, 2, 3, 4, 5]
// // map
a = list(map(str, a))


2022-09-21 22:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.