当前位置: 代码迷 >> python >> 将字典添加到班级
  详细解决方案

将字典添加到班级

热度:77   发布时间:2023-07-16 09:52:19.0

我想让角色从字典中将物品添加到其库存中,但是当我添加它们时,它只给我“价值”的回报,而不是“键”的回报。 我想在游戏的不同部分都使用这两种方式,例如“您拿着'钥匙',它确实'珍视'伤害”。

我想我知道这是在添加字典“值”,因为我的库存类型是“列表”,但是很难找到添加字典项的简单方法。

先谢谢您的帮助!

from random import randint

class Character:
    # Instantiates each character with personality traits
    def __init__(self, name, health, lives, gender, inventory):
        self.name = name
        self.health = int(health)
        self.lives = int(lives)
        self.gender = gender
        self.inventory = []


inventoryitems = {
    'Breadstick': randint(0,5), 
    'Magic Axe': randint(50,100), 
    'Tiny Fists': randint(0,25),
    'Sword': randint(15,30)
    }

player = Character("Kate", 100, 3, 'female',None)

player.inventory.append(inventoryitems['Magic Axe'])
player.inventory.append(inventoryitems['Breadstick'])
print(player.inventory)

您可以使用函数items()来同时遍历键和值:

from random import randint

class Character:
    # Instantiates each character with personality traits
    def __init__(self, name, health, lives, gender, inventory):
        self.name = name
        self.health = int(health)
        self.lives = int(lives)
        self.gender = gender
        self.inventory = []


inventoryitems = {
    'Breadstick': randint(0,5), 
    'Magic Axe': randint(50,100), 
    'Tiny Fists': randint(0,25),
    'Sword': randint(15,30)
}

player = Character("Kate", 100, 3, 'female',None)

# item will be a (key, value) pair
for item in inventoryitems.items():
    player.inventory.append(item)

# or if you only want to add specific items
items_to_add = ['Breadstick', 'Magic Axe']
for item in items_to_add:
    player.inventory.append((item, inventoryitems[item]))

print(player.inventory)

将打印例如

[('Breadstick', 5), ('Magic Axe', 51), ('Tiny Fists', 21), ('Sword', 17), ('Breadstick', 5), ('Magic Axe', 51)]

请注意,两次添加项目不会将新的随机值应用于每个随机值,这可能不是您想要的。

在您的班级中使用字典很简单,然后您可以使用player.inventory.keys()按名称生成项目列表,稍后还可以通过player.inventory ['object_name']以非常简单快速的方式访问项目

from random import randint

class Character:
    # Instantiates each character with personality traits
    def __init__(self, name, health, lives, gender, inventory):
        self.name = name
        self.health = int(health)
        self.lives = int(lives)
        self.gender = gender
        self.inventory = {}


inventoryitems = {
    'Breadstick': randint(0,5), 
    'Magic Axe': randint(50,100), 
    'Tiny Fists': randint(0,25),
    'Sword': randint(15,30)
    }

player = Character("Kate", 100, 3, 'female',None)

player.inventory['Magic Axe'] = inventoryitems['Magic Axe']
player.inventory['Breadstick'] = inventoryitems['Breadstick']
print(player.inventory)
  相关解决方案