Map with Lambdas
Now that we’ve seen how to use map with a normally defined function, let’s try it with a lambda function this time. As map requires a function as the first parameter, we can simply program a lambda in place of the name of a defined function. We can also type convert it on the same line:
# using a map function with lambdas temps = [ 12.5, 13.6, 15, 9.2 ] converted_temps = list( map( lambda C : (9/5) * C + 32, temps) ) # type convert the map object right away print(converted_temps)
Go ahead and run the cell. We’ll get the same output as we did before but in far less lines of code. This is the beauty of combining these two concepts. The lambda function takes in each item as the map function iterates over the temps list and returns the converted value. The same process that we’re performing can be found in the lines of code in the following:
>>> def convertDeg(degrees):
>>> converted = [ ] >>> for degree in degrees:
>>> result = (9/5) * degree + 32
>>> converted.append(result)
>>> return converted
>>> temps = [ 12.5, 13.6, 15, 9.2 ]
>>> converted_temps = convertDeg(temps)
>>> print(converted_temps)
As you can see, the use of lambda functions and map help to reduce the lines of code used when we need to alter our data.
Filter Without Lambdas
The filter function is useful for taking a collection of data and removing any information that you don’t need. Like the map function, it takes in a function and an iterable data type and returns a filter object. This object can be converted into a working list like we did with our map object. Let’s use the same data and filter out any degrees that aren’t above 55 degrees Fahrenheit:
# using the filter function without lambda functions, filter out temps below 55F def filterTemps(C):
converted = (9/5) * C + 32
return True if converted > 55 else False # use ternary operator temps = [ 12.5, 13.6, 15, 9.2 ] filtered_temps = filter(filterTemps, temps) # returns filter object print(filtered_temps)
filtered_temps = list(filtered_temps) # convert filter object to list of filtered data
print(filtered_temps)
Go ahead and run the cell. The first output results in “”, like our map object output. The second statement results in the output of “[56.48, 59]”. When we used filter and passed in temps, it looped over the list one item at a time. It would then pass each item into the filterTemps function, and whether the return was True or False, it would add the item to the filter object. It’s not until we type convert the object into a list that we’re able to output the data. Using a lambda function can reduce the lines of code needed even further.
Do'stlaringiz bilan baham: |