简体   繁体   English

Map function 或 lambda 在 ZA7F5F35426B9237411FC92317B 中无法正常工作

[英]Map function or lambda does not work as expected in Python

My code does not work as expected.我的代码没有按预期工作。 My partial code looks like this:我的部分代码如下所示:

lst_of_players = []

class Player:
    def __init__(self, username):
        self.username = username
        self.level = 1
        lst_of_players.append(self)

    def level_up(self):
        self.level += 1


player1 = Player("Player 1")
player2 = Player("Player 2")
player3 = Player("Player 3")

def level_up_all_players():
    map(lambda player: player.level_up(), lst_of_players)

I thought the players' levels would be leveled up by 1 when i call level_up_all_players func, but it does not.我以为当我调用 level_up_all_players 函数时,玩家的等级会提升 1,但事实并非如此。 When I print the levels of players, they still had the levels they had before calling the function.当我打印玩家的等级时,他们仍然拥有调用 function 之前的等级。

map() used to work as you expected in Python 2.7, but now map() is lazy in Python 3.x, so you have to force it to work. map()曾经在 Python 2.7 中按预期工作,但现在map()在 Python 3.x 中是惰性的,所以你必须强制它工作。 Put the last line of your level_up_all_players() inside list() , like this:level_up_all_players()的最后一行放在list()中,如下所示:

list(map(lambda player: player.level_up(), lst_of_players))

However , this is not recommended.但是,不建议这样做。 It's not usually a good practice to use map() just for the side effects (in your case, code is just adding 1 to player's level).仅将map()用于副作用通常不是一个好习惯(在您的情况下,代码只是将 1 添加到玩家的级别)。 Normally, you work with the result that is produced using map() .通常,您使用使用map()生成的结果。

So, I really think you should use for loop for this kind of work, and it's easier to read than map with lambda for me and for many other people:所以,我真的认为你应该为这种工作使用for循环,对于我和其他许多人来说,它比maplambda更容易阅读:

for player in lst_of_players:
    player.level_up()

Update更新

If you really want to achieve the same thing with just one line, you can do this:如果你真的想用一行代码来达到同样的效果,你可以这样做:

for player in lst_of_players: player.level_up()

And I found a similar SO post that is about map() in Python.我在 Python 中发现了一个类似的关于map()的帖子。 Please take a look at it: link to the post请看一下: 链接到帖子

map is lazy: the function isn't applied until you actually iterate over the map object. map是惰性的:在实际迭代map ZA8CFDE6313149EB2666ZB8 之前,不会应用 function。

Neither map nor a list comprehension, though, should be used solely for the side effect of the function being called on a value.但是, map和列表推导都不应仅用于对值调用 function 的副作用。 Only use it if you want the return value of each function call.仅当您想要每个 function 调用的返回值时才使用它。 Just use a regular for loop instead:只需使用常规for循环:

for p in lst_of_players:
    p.level_up()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM