本文介绍了for循环与map的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,标题是有区别的.现在应用于我的场景:让我们考虑一个类Dummy:

From the title, yes there is a difference. Now applied to my scenario: let's consider a class 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仍为空.

I indeed get D.attached = [1, 2, 3, 4]. But if I map the function attach_item to the items, D.attached remains empty.

map(D.attach_item, items)

它在做什么?

推荐答案

一个非常有趣的问题,它的答案很有趣.

A very interesting question which has an interesting answer.

map函数返回一个可迭代的Map对象. map正在懒惰地执行其计算,因此除非您对该对象进行迭代,否则该函数将不会被调用.

The map function returns a Map object which is iterable. map is performing its calculation lazily so the function wouldn't get called unless you iterate that object.

因此,如果您这样做:

x = map(D.attach_item, items)
for i in x:
    continue

将显示预期结果.

这篇关于for循环与map的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 18:22