变量游戏中有一个对象列表。
for g in games:
if g.clam ==5: g.new_var=1
if g.clam ==4: g.new_var=0
如何使用map()函数获得上述功能?我尝试了类似下面的内容,但我认为它并不接近正确的方式。
def assign_var(clam):
if clam==5: return 1
if clam==4: return 0
games.new_var = map(assign_var, games.clam)
答案 0 :(得分:1)
在assign_var
功能
>>> def assign_var(instance):
... if instance.clam == 5:
... instance.new_var = 1
... elif instance.clam == 4:
... instance.new_var = 0
...
>>> map(assign_var, games)
[None, None, None] # Intentional. It will modify the list "games" in place.
>>> for ins in games:
... print ins.new_var
...
0
1
0
但实际上,这不是应该使用map()
的内容。 map()
应该用于可以使用已更改的数据返回的列表,而您无法使用类的属性执行此操作。
一个简单的for循环应该绝对正确:
for ins in games:
if ins.clam == 5:
instance.new_var = 1
elif instance.clam == 4:
instance.new_var = 0
请注意,请记住稀疏优于密集;)。
答案 1 :(得分:0)
目前还不清楚为什么要在这里使用map()
。如果你正在改变games
一个简单的for
- 循环就足够了。
map()
更适合创建新的list
(即使这样,列表理解也会更受欢迎)。
我还认为dict
是定义映射的一种更简洁的方法,因为它不需要维护。这可以包含在您的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)]
为什么呢?请参阅The fate of reduce()
in Python 3000。