匿名函式與 map 函式

  1. 內建 map() 函式依序將 iterable 的元素傳入 function,然後將 function 執行的結果組成新的物件傳回。
    map( function, iterable)
    
  2. 範例:使用匿名函式對串列元素計算其平方值。
    [dywang@deyu zzz]$ cat function9.py 
    #!/usr/bin/python3
    # coding: utf-8
    
    xlist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    squarelist = map(lambda x : x**2, xlist)
    
    print("square of xlist:", squarelist)
    
  3. 執行結果:python3 map 回傳的是 map object at 記憶體位置。
    [dywang@deyu zzz]$ ./function9.py 
    square of xlist: <map object at 0x7f8335e4d208>
    
  4. 要輸出map的結果,必須將其轉換成list。
    [dywang@deyu zzz]$ cat function9a.py 
    #!/usr/bin/python3
    # coding: utf-8
    
    xlist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    squarelist = list(map(lambda x : x**2, xlist))
    
    print("square of xlist:", squarelist)
    
  5. 執行結果:印出 map 的結果。
    [dywang@deyu zzz]$ ./function9a.py 
    square of xlist: [1, 4, 9, 16, 25, 36, 49, 64, 81]