3 回答
TA贡献1833条经验 获得超4个赞
map
map(f, iterable)
[f(x) for x in iterable]
map
[(a, b) for a in iterable_a for b in iterable_b]
result = []for a in iterable_a: for b in iterable_b: result.append((a, b))
TA贡献2019条经验 获得超9个赞
map
map
.
map
def map(func, iterable): for i in iterable: yield func(i)
yield
map
[func(i) for i in iterable]
>>> a = "hello, world" >>> list(a)['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']>>> tuple(a)('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')
map
map
>>> a = ["foo", "bar", "baz"]>>> list(map(list, a))[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]
map(list, a)
list
for
sum
>>> [list(b) for b in a][['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]
TA贡献1803条经验 获得超6个赞
map通过将函数应用于源的每个元素创建一个新列表:
xs = [1, 2, 3]
# all of those are equivalent — the output is [2, 4, 6]
# 1. map
ys = map(lambda x: x * 2, xs)
# 2. list comprehension
ys = [x * 2 for x in xs]
# 3. explicit loop
ys = []
for x in xs:
ys.append(x * 2)
正元map等效于将可迭代的输入压缩到一起,然后对中间压缩列表的每个元素应用转换函数。它是不笛卡尔产品:
xs = [1, 2, 3]
ys = [2, 4, 6]
def f(x, y):
return (x * 2, y // 2)
# output: [(2, 1), (4, 2), (6, 3)]
# 1. map
zs = map(f, xs, ys)
# 2. list comp
zs = [f(x, y) for x, y in zip(xs, ys)]
# 3. explicit loop
zs = []
for x, y in zip(xs, ys):
zs.append(f(x, y))
我用过zip在这里,但是map实际上,当可迭代性大小不同时,行为实际上略有不同-正如其文档中所指出的,它扩展了可访问性以包含None.
添加回答
举报