0

变量游戏中有一个对象列表。

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)
4

2 回答 2

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

请注意,请记住稀疏比密集更好;)。

于 2013-08-31T03:08:31.003 回答
0

目前尚不清楚您为什么要在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()

于 2013-08-31T06:20:54.113 回答