繁体   English   中英

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

[英]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 函数时,玩家的等级会提升 1,但事实并非如此。 当我打印玩家的等级时,他们仍然拥有调用 function 之前的等级。

map()曾经在 Python 2.7 中按预期工作,但现在map()在 Python 3.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 中发现了一个类似的关于map()的帖子。 请看一下: 链接到帖子

map是惰性的:在实际迭代map ZA8CFDE6313149EB2666ZB8 之前,不会应用 function。

但是, map和列表推导都不应仅用于对值调用 function 的副作用。 仅当您想要每个 function 调用的返回值时才使用它。 只需使用常规for循环:

for p in lst_of_players:
    p.level_up()

暂无
暂无

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

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