映射函数或 lambda 在 Python 中未按预期工作

Map function or lambda does not work as expected in Python

我的代码没有按预期工作。我的部分代码如下所示:

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)

我以为当我调用level_up_all_players func 时玩家的等级会提高1,但事实并非如此。 当我打印玩家等级时,他们仍然拥有调用该函数之前的等级。

map()曾经在Python 2.7中按你的预期工作,但现在map()在Python3.x中很懒惰,所以你必须强制它工作。把你的 level_up_all_players() 的最后一行放在 list() 里面,像这样:

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

但是,不推荐这样做。仅针对副作用使用 map() 通常不是一个好的做法(在您的情况下,代码只是将玩家的等级加 1)。 通常,您使用 map().

生成的结果

所以,我真的认为你应该为这种工作使用 for 循环,而且它比 maplambda 对我和其他许多人来说更容易阅读:

for player in lst_of_players:
    player.level_up()

更新

如果你真的想只用一行实现同样的事情,你可以这样做:

for player in lst_of_players: player.level_up()

而且我在 Python 中发现了一个类似的 SO post,大约是 map()。请看一下:link to the post

map 是惰性的:在您实际遍历 map 对象之前不会应用该函数。

但是,map 和列表推导式都不应该仅用于对值调用函数的副作用。仅当您需要每个函数调用的 return 值时才使用它。只需使用常规 for 循环即可:

for p in lst_of_players:
    p.level_up()