python3中使用map踩過的坑~
阿新 • • 發佈:2018-11-10
先來看下Python2.7中對map的簡單使用:
a = [[1],[2],[3],[4]]
b = map(set, a)
print(type(b))
print(b)
print(len(b))
# 結果如下:
<type 'list'>
[set([1]), set([2]), set([3]), set([4])]
4
然而,python3中是這樣的:
a = [[1],[2],[3],[4]] b = map(set, a) print(type(b)) print(b) print(len(b)) # 程式報錯如下: <class 'map'> <map object at 0x00000135B2C72160> --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-1-8d7d0caf6576> in <module>() 3 print(type(b)) 4 print(b) ----> 5 print(len(b)) TypeError: object of type 'map' has no len()
可以看到,在python3中map的返回型別是 ‘map’類,它返回的是該物件的記憶體地址,當然長度是沒法求了,如果要求map後的長度,那麼必須將map轉為list,如下:
a = [[1],[2],[3],[4]]
b = list(map(set, a))
print(type(b))
print(b)
print(len(b))
# 結果如下:
<class 'list'>
[{1}, {2}, {3}, {4}]
4
好了,以上就是我踩過的坑坑,下次要記得在python3中 list(map())了!