【问题标题】:Dictionary vs Variable字典与变量
【发布时间】:2013-07-29 01:43:38
【问题描述】:

我目前正在阅读“Python Programming for the Absolute Beginning 3rd Edition”。挑战之一是:

为角色扮演游戏编写 Character Creator 程序。这 应该给玩家一个 30 点的池子来花四个 属性:力量、健康、智慧和敏捷。这 玩家应该能够将池中的积分用于任何 属性,并且还应该能够从 属性并将它们放回池中。

一开始我是用变量写的

pool = 30
strength = 0
health = 0
wisdom = 0
dexterity = 0

这部分是关于列表和字典的。所以我的问题是:以这种方式使用变量更好还是可以使用字典?如果是这样,它更有效吗?即:

attributes = {
             "strength" : 0,
             "health" : 0,
             "wisdom" : 0, 
             "dexterity" : 0
             }

【问题讨论】:

  • 我更喜欢第二个,因为那样你可以循环播放
  • 对于更灵活的方法:属性集合似乎非常适合类,而不是字典或一堆变量
  • 我还没有上过书中的课程,但是我已经看到了一些例子。因此,如果我要上课 def attributes: 并在其中分配所有力量、健康等值。我可以稍后调用它们或使用 attributes.strength、attributes.health 等更改它们?
  • @mccdlibby 是的,您可以创建依赖这些值的其他操作。暂时来说,字典比较灵活,但是学完课后你会发现用字典比较适合解决这个问题

标签: python dictionary python-3.x


【解决方案1】:

简而言之:我会去找字典。

长篇大论:这可能是直接深入研究面向对象编程的一个很好的例子。

#! /usr/bin/python3

class Character:
        class AbilityScoreOutOfBoundsException (Exception): pass

        def __init__ (self, name):
            self.name = name
            self.stats = {k: 1 for k in ['STR', 'DEX', 'WIS', 'INT'] }

        @property
        def strength (self): return self.stats ['STR']

        @property
        def dexterity (self): return self.stats ['DEX']

        @property
        def wisdom (self): return self.stats ['WIS']

        @property
        def intelligence (self): return self.stats ['INT']

        @strength.setter
        def strength (self, amount): self.setStat ('STR', amount)

        @wisdom.setter
        def wisdom (self, amount): self.setStat ('WIS', amount)

        @dexterity.setter
        def dexterity (self, amount): self.setStat ('DEX', amount)

        @intelligence.setter
        def intelligence (self, amount): self.setStat ('INT', amount)

        def setStat (self, which, amount):
            if amount < 1: raise Character.AbilityScoreOutOfBoundsException ('Beware hero! Thou wert about to smite thyself.')
            if self.total + amount - self.stats [which] > 30: raise Character.AbilityScoreOutOfBoundsException ('Beware hero! Thou shalt not grow too mighty.')
            self.stats [which] = amount

        @property
        def total (self): return sum (self.stats.values () )

        def __repr__ (self):
            return '{}\n{}'.format (self.name, '\n'.join ('{}{:>4}'.format (which, self.stats [which] ) for which in ['STR', 'DEX', 'WIS', 'INT'] ) )

a = Character ('Daggeroth')
a.strength += 9
a.dexterity += 9
a.wisdom += 5
a.intelligence += 3
print (a)

【讨论】:

    【解决方案2】:

    Python 中的字典是用哈希表实现的,所以效率在这里不是问题。使用属性字典更好,因为它更灵活。

    例如,如果您想要多个字符,那么您可以简单地拥有一个属性字典列表。在这种情况下使用变量是不可维护的(你需要像player1Health, player2Health, ... 这样的东西)。

    【讨论】:

      【解决方案3】:

      在这种情况下,我宁愿重视可读性而不是效率,因为您可能不会遇到任何与统计查找有关的性能问题。我会说字典看起来更好,因为

      attributes['strength'] += 1
      

      对我来说似乎更有条理。

      【讨论】:

        【解决方案4】:

        为了回答您的确切问题,Python 将变量存储在字典中,因此无论您将它们存储在字典中还是仅作为变量,它在程序运行方式方面都没有太大区别。

        内置函数 globals() 和 locals() 返回存储变量集的字典,这些变量的相应名称建议函数。

        在 Python 程序中存储这些类型的变量的典型方法是构造一个类。我猜想在列表和字典之后的某个时候会介绍类,所以这可能有点超前了。

        这就是为此构造一个类的样子:

            class Character(object):
                def __init__(self):
                    self.charisma = 0
                    self.dexterity = 0
                    self.wisdom = 0
                    self.health = 0
                    self.pool = 30
        

        这有一些优点,但一个很容易看出的优点是它允许您轻松创建多个字符。

            alice = Character()
            bob = Character()
        

        alice 和 bob 都以它们自己的相关变量副本启动。 Python 还将类变量存储在字典中。所以 alice.charisma += 1 对 bob.charisma 没有任何影响。

        alice.__dict__ 将是包含每个变量的 alice 副本的字典。

        【讨论】:

          【解决方案5】:

          我认为使用变量将是解决此问题的更有效方法。观察:

                              print(""""
                                    1. strength \n
                                    2 Health\n
                                3. wisdom\n
                                4. dexterity
                                5. remove 1 strength for point
                                6. remove 1 health for point
                                7. Remove 1 wisdom for point
                                8. remove 1 dexterity for point
                                 """)
          
                                   points=30
                                   strength=0
                                   health=0
                                   wisdom=0
                                   dexterity=0
                                   default=1
          
                                  while default:
          
                                   choice=int(input("Select attributes that you want:"))
                                      if choice==1:
                                       strength+=1
                                       points-=1
                                       print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ")
          
                                     elif choice==2:
                                      health+=1
                                      points-=1
                                      print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)
          
                                     elif choice==3:
                                      wisdom+=1
                                      points-=1
                                      print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)
          
                                    elif choice==4:
                                     dexterity+=1
                                     points-=1
                                     print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)
          
                                    elif oc==5:
                                     strength-=1
                                     points+=1
                                     print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)
          
                                   elif oc==6:
                                    health-=1
                                    points+=1
                                    print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)
          
                                   elif oc==7:
                                    wisdowm-=1
                                    points+=1
                                    print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)
          
                                  elif oc==8:
                                   dexterity-=1
                                   points+=1
                                   print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)
          

          当然你也可以使用字典,但是变量的想法要容易得多,编程就是要效率。

          【讨论】:

            猜你喜欢
            • 2013-05-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-04-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多