2

python map不一样应用

 1 year ago
source link: https://blog.51cto.com/u_14967494/5931281
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
map(function, iterable, ...)

function: 针对每个迭代对象的函数

iterable 可迭代对象

注意: function 中参数和iterable个数对应

单个可迭代对象(不常用)

list(map(lambda x:x*2, range(10)))
list(map(str, range(10)))

单个可迭代对象多数可以直接使用列表推倒式更加方便。

多个可迭代对象(常用)

案例1:列表中每个元素为dict的公共键

from random import randint, sample
from functions import reduce

l1 = [{item: randint(1, 5) for item in sample('abcdefg', randint(4, 5))} for _  in range(5)]
reduce(lambda a, b: a & b, map(dict.keys, l1))
a1 = [1, 2, 3]
a2 = [1, 2, 3]
a3 = [1, 2, 3, 5]
list(map(lambda a, b, c: a + b + c, a1, a2, a3))

zip、filter 知道就行


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK