我的代碼沒有按預期作業。我的部分代碼如下所示:
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,但事實并非如此。當我列印玩家的級別時,他們仍然擁有呼叫該函式之前的級別。
uj5u.com熱心網友回復:
map()曾經在 Python 2.7 中按預期作業,但現在map()在 Python 3.x 中很懶惰,因此您必須強制它作業。把你的level_up_all_players()inside的最后一行list(),像這樣:
list(map(lambda player: player.level_up(), lst_of_players))
但是,不建議這樣做。map()僅用于副作用通常不是一個好習慣(在您的情況下,代碼只是將 1 添加到玩家的級別)。通常,您使用使用map().
所以,我真的認為你應該使用for回圈對這種作業,而且更容易比閱讀map與lambda我和許多其他人:
for player in lst_of_players:
player.level_up()
更新
如果你真的想用一行代碼來實作同樣的事情,你可以這樣做:
for player in lst_of_players: player.level_up()
我發現了一個類似的關于map()Python 的SO 帖子。請看一下:鏈接到帖子
uj5u.com熱心網友回復:
map懶惰:在您實際迭代map物件之前,不會應用該函式。
map但是,串列推導式和串列推導式都不應僅用于對值呼叫函式的副作用。僅當您想要每個函式呼叫的回傳值時才使用它。只需使用常規for回圈:
for p in lst_of_players:
p.level_up()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377184.html
上一篇:檢查嵌套json鍵的值
下一篇:決議JsonArray回應資料
