python代码中map,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']

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']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值