在变量游戏中有一个对象列表。
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)发布于 2013-08-31 11:08:31
在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请注意,请记住,稀疏比密集要好;)。
发布于 2013-08-31 14:20:54
现在还不清楚你为什么要在这里使用map()。如果您要对games进行突变,那么一个简单的for-loop就足够了。
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。
https://stackoverflow.com/questions/18544036
复制相似问题