1. 程式人生 > >13 python3 中使用map函式返回相應的列表(python2和3返回結果不同的問題)

13 python3 中使用map函式返回相應的列表(python2和3返回結果不同的問題)

map()是 Python 內建的高階函式,它接收一個函式 f 和一個 list,並通過把函式 f 依次作用在 list 的每個元素上,得到一個新的 list 並返回。

例如:將列表中的資料都平方

def f(x):
    return x*x
print  map(f, [1, 2, 3,])

python2 輸出

[1, 4, 9,]

python3輸出

<map object at 0x0000022E1412A080>

python3中使用map函式與python2中使用map函式返回的內容不一致
使用python2的程式碼呼叫map函式發現返回的並不是列表,而是這樣的

<map object at 0x000002A56FDDA048>

為了讓他顯示正常,我到網上查詢發現有大神解決了這個問題,使用list轉換成列表既可以顯示正常
如下:

def f(x):
    return x*x
print  (list(map(f, [1, 2, 3,])))

輸出:

[1, 4, 9,]

例2:將list1中的資料轉換成整型資料

 def  f(x):
     x = int(x)
     return x
list1= ['1','2','3']
print('原列表為字串:',list1)
list2 =  map(f,list1)
print('新列表為整型資料:',list(list2))