从标题来看,是的,有区别。现在应用于我的场景:让我们考虑一个类 Dummy
:
class Dummy:
def __init__(self):
self.attached = []
def attach_item(self, item):
self.attached.append(item)
如果我使用这个:
D = Dummy()
items = [1, 2, 3, 4]
for item in items:
D.attach_item(item)
我确实得到了 D.attached = [1, 2, 3, 4]
。但是如果我将函数 attach_item
映射到 items
,D.attached
仍然为空。
map(D.attach_item, items)
它在做什么?
最佳答案
一个非常有趣的问题,有一个有趣的答案。
map
函数返回一个可迭代的 Map 对象。 map
正在延迟执行其计算,因此除非您迭代该对象,否则该函数不会被调用。
如果你这样做:
x = map(D.attach_item, items)
for i in x:
continue
会出现预期的结果。
关于python - 'for' 循环和映射之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51671132/