將 lambda() 與 map() 搭配使用
在 Python 中,map() 會把指定函式套用到可疊代物件(list、tuple 等)中的每個元素,並回傳結果的序列。map() 的一般語法是 map(fun, iter)。我們也可以在 map() 中使用 lambda 函式。若需要 map() 搭配 lambda() 的一般說明,請參考影片 1.7 的第 5 張投影片。
在這個練習中,你會在內建的 map() 函式中使用 lambda,把清單中的所有數字平方。
本練習屬於課程
使用 PySpark 的 Big Data 基礎
練習說明
- 列印環境中已提供的
my_list。 - 使用
map()與lambda()將my_list的每個元素平方。 - 列印
map函式的結果。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Print my_list in the console
print("Input list is", ____)
# Square all numbers in my_list
squared_list_lambda = list(____(lambda x: ____, my_list))
# Print the result of the map function
print("The squared numbers are", ____)