目前尚不清楚您为什么要在map()
此处使用。如果你正在变异games
一个简单的for
-loop 就足够了。
map()
更适合创建一个新的list
(即使这样,列表理解也是首选)。
我还认为 adict
是一种定义映射的更简洁的方式,因为它更容易维护。这可以包含在您的Game
课程中。
这是一个例子:
#!/usr/bin/env python
class Game(object):
clam_to_new_var = {
4: 0,
5: 1,
}
def __init__(self, clam):
self.clam = clam
@property
def new_var(self):
return Game.clam_to_new_var.get(self.clam, None)
def __str__(self):
return 'Game with clam "{}" has new_var "{}"'.format(
self.clam,
self.new_var,
)
if __name__ == '__main__':
games = map(Game, xrange(10))
for g in games:
print g
样本输出:
Game with clam "0" has new_var "None"
Game with clam "1" has new_var "None"
Game with clam "2" has new_var "None"
Game with clam "3" has new_var "None"
Game with clam "4" has new_var "0"
Game with clam "5" has new_var "1"
Game with clam "6" has new_var "None"
Game with clam "7" has new_var "None"
Game with clam "8" has new_var "None"
Game with clam "9" has new_var "None"
我离开map()
了那个例子,但在生产代码中,我更喜欢:
games = [Game(clam) for clam in range(10)]
为什么?请参阅Python 3000 中的命运reduce()
。