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
After declaring this class , I wrote this code :
>>> 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']
I am unable to understand how the map function is working behind the hood , why is it returning a list with all None , but when I check f.goodFood the elements have been added there ?
解决方案
map applies a function on an iterable and returns a new list where the function was applied on each item.
In your case, it shows None because f.addGoodFood function returns nothing.
For testing purposes change addGoodFood this way:
def addGoodFood(self, food):
self.goodFood.append(food)
return "test"
and see:
>>> map(f.addGoodFood, ['SPAM', 'Eggs', 'Bacon', 'Rat', 'Spring Surprise'])
['test', 'test', 'test', 'test', 'test']