1. 程式人生 > >Python3下map函式的顯示問題

Python3下map函式的顯示問題

map函式是Python裡面比較重要的函式,設計靈感來自於函數語言程式設計。Python官方文件中是這樣解釋map函式的:
map(function, iterable, …)
Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted.

即map函式接收的第一個引數為一個函式,可以為系統函式例如float、或者def定義的函式、或者lambda定義的函式均可。

舉一個簡單的例子,下面這個例子在Python2.7下是可以正常顯示的:

ls = [1,2,3]
rs = map(str, ls)

#輸出結果
[‘1’, ‘2’, ‘3’]

lt = [1, 2, 3, 4, 5, 6]
def add(num):
    return num + 1
rs = map(add, lt)
print rs

#輸出結果
[2,3,4,5,6,7]

但是在Python3下我們輸入:

ls=[1,2,3]
rs=map(str,ls)
print(rs)

#輸出結果
<map at 0x3fed1d0>

這是Python3下發生的一些新的變化,如果我們想得到需要的結果需要這樣寫:、

ls=[1,2,3]
rs=map(str,ls)
print(list(rs))

這樣就會正常輸出