What’s map()?

What’s map()?

It’s a tool that lets you apply a function to each item in an iterable effortlessly.

Python’s map() function lets you apply a function to each item in any iterable effortlessly, whether it’s a list, tuple, set, or even a string.

How to Use It:

  1. Create a Function: For example, to double numbers:

def double(x):
    return x * 2        

2. Have a List: Like this:

numbers = [1, 2, 3, 4]        

3. Apply map():

doubled = map(double, numbers)        

4. See the Results:

print(list(doubled))  # Output: [2, 4, 6, 8]        

Why Use map()? It makes applying a function to a list quick and clean.

Here are five Python programs demonstrating different practical applications of the map() function.

1. Converting Temperatures from Celsius to Fahrenheit

Convert a list of temperatures from Celsius to Fahrenheit.

def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

celsius_temps = [0, 10, 20, 30, 40]
fahrenheit_temps = map(celsius_to_fahrenheit, celsius_temps)
print(list(fahrenheit_temps))  # Output: [32.0, 50.0, 68.0, 86.0, 104.0]        

2. Squaring a List of Numbers

Square each number in a list.

def square(number):
    return number ** 2

numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers))  # Output: [1, 4, 9, 16, 25]        

3. Converting a List of Strings to Uppercase

Convert all strings in a list to uppercase.

def to_uppercase(text):
    return text.upper()

words = ['apple', 'banana', 'cherry']
uppercase_words = map(to_uppercase, words)
print(list(uppercase_words))  # Output: ['APPLE', 'BANANA', 'CHERRY']        

4. Adding a Fixed Value to Each Element in a List

Add 10 to each number in a list.

def add_ten(number):
    return number + 10

numbers = [5, 10, 15, 20]
updated_numbers = map(add_ten, numbers)
print(list(updated_numbers))  # Output: [15, 20, 25, 30]        

5. Formatting Dates from YYYY-MM-DD to MM/DD/YYYY

Convert date strings from YYYY-MM-DD format to MM/DD/YYYY.

def format_date(date_str):
    year, month, day = date_str.split('-')
    return f"{month}/{day}/{year}"

dates = ['2024-01-01', '2024-02-14', '2024-12-31']
formatted_dates = map(format_date, dates)
print(list(formatted_dates))  # Output: ['01/01/2024', '02/14/2024', '12/31/2024']        

Each program uses the map() function to apply a specific transformation to every item in a list, showcasing how versatile and useful map() can be for different tasks

Give it a try and see the magic for yourself!

要查看或添加评论,请登录

社区洞察

其他会员也浏览了