字典与变量

时间:2013-07-29 01:43:39

标签: python dictionary python-3.x

我目前正在阅读“Absolute Beginning 3rd Edition的Python编程”。其中一个挑战是:

  

为角色扮演游戏编写角色创建程序。该   球员应该获得30分的积分,花费四分   属性:力量,健康,智慧和敏捷。该   玩家应该能够从游泳池中消费积分   属性,也应该能够从一个点   属性并将它们放回池中。

起初我用变量

写了它
pool = 30
strength = 0
health = 0
wisdom = 0
dexterity = 0

本节介绍列表和词典。所以我的问题是:以这种方式使用变量或者是否可以使用字典更好?如果是这样,它更有效率吗?即:

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

5 个答案:

答案 0 :(得分:3)

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

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

#! /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)

答案 1 :(得分:1)

在这种情况下,我更倾向于重视可读性而不是效率,因为您可能不会遇到任何性能查询问题。我会说字典看起来更好,因为

attributes['strength'] += 1

对我来说似乎更有条理。

答案 2 :(得分:1)

为了回答您的确切问题,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每个变量副本的字典。

答案 3 :(得分:0)

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

例如,如果您想要多个字符,那么您只需要一个属性字典列表。在这种情况下使用变量是不可维护的(您需要player1Health, player2Health, ...)。

答案 4 :(得分:0)

我认为使用变量将是更有效的方法。观察:

                    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)

当然你也可以使用词典,但变量想法更容易,编程就是效率。