map()函數的用法


map()函數的用法

map()函數作用:對列表里每個元素都用函數計算,返回一個新列表。

map()函數有兩類參數:一個函數和若干列表。

這個函數有幾個參數,map()后面就有幾個列表。

1 - 一個函數處理一個列表

my_list_0 = map(lambda x: x * x, [1, 2, 3, 4, 5, 6])
for i in my_list_0:
    print(i)

運行結果:

1
4
9
16
25
36
特殊用法
my_list_0 = map(int,'12345')
for i in my_list_0:
    print(type(i))
    print(i)

運行結果:

<class 'int'>
1
<class 'int'>
2
<class 'int'>
3
<class 'int'>
4
<class 'int'>
5

2 - 一個函數處理多個列表

my_list_1 = map(lambda x, y: x ** y, [1, 2, 3], [1, 2, 3])
for i in my_list_1:
    print(i)

運行結果:

1
4
27

3 - 一個函數處理多個列表,列表長度不一致,可以

my_list_3 = map(lambda x, y: (x ** y, x + y), [1, 2, 3], [1, 2])
for i in my_list_3:
    print(i)

運行結果:

(1, 2)
(4, 4)

4 - 一個函數處理多個列表,列表元素類型不一致,不可以

my_list_4 = map(lambda x, y: (x ** y, x + y), [1, 2, 3], [1, 2,'a'])
for i in my_list_4:
    print(i)

運行結果:

TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'
(1, 2)
(4, 4)

5 - 函數為None,列表不限

print(map(None,[1,2,3,4,5,6]))
print(map(None,[2,3,4],[1,2,3]))

運行結果

<map object at 0x006594C0>
<map object at 0x00659AC0>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM