Python中的Map方法 [英] Map method in python
本文介绍了Python中的Map方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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']
我无法理解map函数是如何在后台运行的,为什么它返回包含所有None
的列表,但是当我检查f.goodFood
时,元素是否已添加到列表中?
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
在可迭代对象上应用函数,并返回一个新列表,其中该函数应用于每个项目.
map
applies a function on an iterable and returns a new list where the function was applied on each item.
在您的情况下,它显示None
,因为f.addGoodFood
函数什么都不返回.
In your case, it shows None
because f.addGoodFood
function returns nothing.
出于测试目的,请按以下方式更改addGoodFood
:
For testing purposes change addGoodFood
this way:
def addGoodFood(self, food):
self.goodFood.append(food)
return "test"
并查看:
>>> map(f.addGoodFood, ['SPAM', 'Eggs', 'Bacon', 'Rat', 'Spring Surprise'])
['test', 'test', 'test', 'test', 'test']
这篇关于Python中的Map方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文