3 回答

TA貢獻1833條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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條經(jīng)驗 獲得超6個贊
map通過將函數(shù)應(yīng)用于源的每個元素創(chuàng)建一個新列表:
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等效于將可迭代的輸入壓縮到一起,然后對中間壓縮列表的每個元素應(yīng)用轉(zhuǎn)換函數(shù)。它是不笛卡爾產(chǎn)品:
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.
添加回答
舉報