map()

Meetod map() teostab mingit kasutaja poolt määratud tehet igale elemendile algsest andmekogumist. Näiteks on meil järjend numbritest ja me tahame saada sellest uut järjendit, kus iga uus number võrdub algse järjendi numbri ruuduga:

# Data to change
input_list = [1, 2, 3, 4]

# Defining changing method
def change_method(number: int) -> int:
    # Return the same number squared
    return number ** 2

# Changing the values in input_list, outcome is <map> object
mapped = map(change_method, input_list)

# Converting the <map> object to list and printing its contents
print(list(mapped))  # --> [1, 4, 9, 16]

Ja kasutades lambda-t:

# no pec input_list = [1, 2, 3, 4] mapped = map(lambda number: number ** 2, input_list) print(list(mapped)) # --> [1, 4, 9, 16]

Veel üks näide:

# no pec # Data to change input_list = ["Clean", "code", "is", "good", "code"] # Changing the values in input_list, outcome is object # Replacing word "is" to "=" mapped = map(lambda word: "=" if word == "is" else word, input_list) # Converting the object to list and joining contents to string print(" ".join(list(mapped))) # --> Clean code = good code # Or ... (isn't quite clean code though) print(" ".join(list(map(lambda word: "=" if word == "is" else word, input_list)))) # --> Clean code = good code