python中的map方法

abk*_*kds 8 python functional-programming list

class FoodExpert:
    def init(self):
        self.goodFood = []
    def addGoodFood(self, food):
        self.goodFood.append(food)
    def likes(self, x):
        return x in self.goodFood
    def prefers(self, x, y):
        x_rating = self.goodFood.index(x)
        y_rating = self.goodFood.index(y)
        if x_rating > y_rating:
            return y
        else:
            return x
Run Code Online (Sandbox Code Playgroud)

在声明这个类之后,我编写了这段代码:

>>> f = FoodExpert()
>>> f.init()
>>> map(f.addGoodFood, ['SPAM', 'Eggs', 'Bacon', 'Rat', 'Spring Surprise'])
[None, None, None, None, None]

>>> f.goodFood
['SPAM', 'Eggs', 'Bacon', 'Rat', 'Spring Surprise']
Run Code Online (Sandbox Code Playgroud)

我无法理解地图功能如何在幕后工作,为什么它会返回一个包含所有的列表None,但是当我检查f.goodFood元素是否已添加到那里?

ale*_*cxe 9

map 在iterable上应用一个函数,并返回一个新的列表,其中函数应用于每个项目.

在您的情况下,它显示None因为f.addGoodFood函数不返回任何内容.

出于测试目的,改变addGoodFood方式:

def addGoodFood(self, food):
    self.goodFood.append(food)
    return "test"
Run Code Online (Sandbox Code Playgroud)

并看到:

>>> map(f.addGoodFood, ['SPAM', 'Eggs', 'Bacon', 'Rat', 'Spring Surprise'])
['test', 'test', 'test', 'test', 'test']
Run Code Online (Sandbox Code Playgroud)


iCo*_*dez 5

那是因为addGoodFood没有返回任何东西.让它返回一些东西:

def addGoodFood(self, food):
    self.goodFood.append(food)
    return food
Run Code Online (Sandbox Code Playgroud)

map正在创建一个调用列表中每个项目的结果addGoodFood列表.并且,由于append列表的方法总是返回None,因此您将获得一个列表None.

此外,您可能希望将init功能更改为:

def __init__(self):
    self.goodFood = []
Run Code Online (Sandbox Code Playgroud)

__init__是一种处理类初始化的特殊方法.使用它意味着您不必这样做f.init().