有没有一种方法可以打印列表中类的所有特定元素?

时间:2018-11-17 01:08:35

标签: python python-3.x

标题很糟糕,但希望我能在帖子中解释。创建一个小游戏作为我的python宠物项目,目前正在创建清单。在开发游戏时,一切都还不错……直到制作出能够显示所有玩家库存的功能为止。

    elif (prompt == "examine"):
        print(inventory[1].name)
        gameprompt()

好吧,所以我创建了一个列表,该列表基本上包含 Items 中的一堆类。要调用这些类的name元素,我必须执行类似的操作,否则,我只会得到它的存储位置,这对播放器几乎没有用。我尝试过

    elif (prompt == "examine"):
        print(inventory[].name)
        gameprompt()

以为上面的示例将仅打印所有Item对象的名称,但是存在编译错误,因为我没有指定哪个。所以我尝试了〜

        elif (prompt == "examine"):
            print(inventory[1:1000].name)
            gameprompt()

以为它将打印最多1000个的所有Item对象名称,但是我显然没有,所以我认为可以将名称打印到最新的对象并停止,但是又出现了另一个编译错误从这里...

如果仍然要为列表中的所有类对象打印出类的元素,请告诉我。该游戏的完整代码在这里,尽管我认为您不需要它来帮助我解决问题(它也很大)。

playername = input("What is your name?")
zone = 1
movement = 0
restcounter = 0
searchcounter = 0
class Player:
    def __init__(self, name, hp, mp, atk, xp, dodgerate, atkrate):
        self.name = playername
        self.hp = hp
        self.mp = mp
        self.atk = atk
        self.xp = xp
        self.dodgerate = dodgerate
        self.atkrate = atkrate

class Enemy(Player):
    def __init__(self, name, gold, maxhp, hp, mp, atk, xp):
        self.name = name
        self.gold = gold
        self.maxhp = maxhp
        self.hp = hp
        self.mp = mp
        self.atk = atk
        self.xp = xp
class Items:
    def __init__(self, name, quantity, description, price, weight):
        self.name = name
        self.quantity = quantity
        self.description = description
        self.price = price
        self.weight = weight


Player = Player(playername, 1, 1, 1, 1, 25, 3)
print(Player.name + " has been created. ")



def raceselection():
   raceinput = input("Do you float towards the TEMPLE, CAVE or FOREST?")
    if raceinput == "TEMPLE":
        print("You are now a high elf. High elves utlize a lot of magical power at the cost of being very frail.")
        Player.hp = Player.hp + 24
        Player.mp = Player.mp + 100
        Player.atk = Player.atk + 50
        print("You awaken from your slumber. Your room's walls are gold plated, and you rested on a flat board.")
        print("Out the door, you see many elves with robes praying to some goddess.")
        print("You walk out of your door and into the praying area. You are immediately greeted by a tall man.")
    elif raceinput == "CAVE":
        print("You are now an orc.")
        Player.hp = Player.hp + 1000
        Player.mp = Player.mp + 15
        Player.atk = Player.atk + 50
        print("cave")
    elif raceinput == "FOREST":
        print("You are now a human.")
        Player.hp = Player.hp + 50
        Player.mp = Player.mp + 25
        Player.atk = Player.atk + 25
    else:
        print("You can't float there!")
        raceselection()


raceselection()


inventory = []
def gameprompt():
    global inventory
    global zone
    global movement
    global restcounter
    global searchcounter
    if (movement == 5):
        movement = movement - movement
        zone = zone + 1
        print("You have advanced to zone",zone,"!!!")
        gameprompt()
    if (zone == 1):
        print("Welcome to the first zone! Easy enemies are here with not very good loot./fix grammar, add description of zone/")
    elif (zone == 2):
        print("Hey, it actually travelled to the second zone, awesome!")
    elif (zone == 3):
        print("No way would this actually work!")
    prompt = input("Would you like to walk, search or rest?: ")

    if (prompt == "walk"):
        encounterchance = random.randint(1, 3)
        if (encounterchance == 2):
            if (zone == 1):
                mobspawnrate = random.randint(1,3)
                if (mobspawnrate == 1):
                    Enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
                    print("You have encountered a " + Enemy.name + "!!!")
                elif (mobspawnrate == 2):
                    Enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
                    print("You have encountered a " + Enemy.name + "!!!")
                elif (mobspawnrate == 3):
                    Enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
                    print("You have encountered a " + Enemy.name + "!!!")
        else:
            movement = movement + 1
            print("You have walked a step. You are now at ",movement," steps")
            gameprompt()
    elif (prompt == "search"):
        if (searchcounter == 3):
            print("You cannot search this area anymore! Wait until you reach the next zone!")
            gameprompt()
        else:
            searchchance = random.randint(1, 5)
            if (searchchance == 1 or 2 or 3 or 4):
                searchcounter = searchcounter + 1
                print(searchcounter)
                print("You have found something!")
                searchchance = random.randint(1,4)
                if (searchchance == 1 or 2):
                    inventory.append(Items("Old Boot", 1, "An old smelly boot. It's a mystery as to who it belongs to...", 5, 50))
                    print("You have found a Boot!")
                    print(inventory)
                elif(searchchance == 3):
                    inventory.append(Items("Shiny Boot", 1, "Looks like a boot that was lightly worn. You could still wear this.", 5, 50))
                    print(inventory)
                    print("You have found a Shiny Boot!")
                elif(searchchance == 4):
                    inventory.append(Items("Golden Boot", 1, "It's too heavy to wear, but it looks like it could sell for a fortune!", 5, 50))
                    print("You have found a Golden Boot?")
                    print(inventory)
            else:
                searchcounter = searchcounter + 1
                print(searchcounter)
                print("You did not find anything of value")
           gameprompt()
    elif (prompt == "rest"):
        if (restcounter == 1):
            print("Wait until you reach the next zone to rest again!")
            gameprompt()
        else:
        # Add a MaxHP value to the player later, and the command rest will give 25% of that HP back.
            Player.hp = Player.hp + (Player.hp / 5)
            print("You have restored ",(Player.hp / 5)," hit points!")
            restcounter = restcounter + 1
            gameprompt()
    elif (prompt == "examine"):
        print(inventory[1].name)
        gameprompt()
    gameprompt()

1 个答案:

答案 0 :(得分:1)

列表理解或map在这里可以完美地工作:

print([item.name for item in inventory])

理解将迭代列表,并用for之前的任何部分将列表中的每个元素“替换”。在这种情况下,它是item.name

°实际上,它不会替换原始列表中的元素。它将评估为包含已替换项目的新列表。