打印最后一项添加到列表中

时间:2016-05-19 13:25:23

标签: python

Okey,所以我正在学习python,我试图创建这个基本的挑选销售游戏......

import random
global gold
gold = 0

class Fruit:
    def __str__(self):
        return self.name

    def __repr__(self):
        return self.name

class Apple(Fruit):
    def __init__(self):
        self.name = "Apple"
        self.desc = "An Red Apple!"
        self.value = "2 Gold"

class Grapes(Fruit):
    def __init__(self):
        self.name = "Grapes"
        self.desc = "Big Green Grapes!"
        self.value = "4 Gold"

class Banana(Fruit):
    def __init__(self):
        self.name = "Banana"
        self.desc = "Long, Fat Yellow Bananas"
        self.value = "5 Gold"

class Orange(Fruit):
    def __init__(self):
        self.name = "Orange"
        self.desc = "Big Orange Orange"
        self.value = "7 Gold"


inventory = []

print ("Fruits!")
print ("To see your inventroy press: i")
print ("To sell fruits press: s")
print ("To pick fruits press: p")

def action():
    return input("Action: ")


def i ():
    print ("Your Inventory: ")
    print ("*" + str(inventory))

def p ():
    pick = [Apple(), Orange(), Grapes(), Banana()]
    inventory.append (random.choice(pick))

def s ():
    print ("...")

while True:
    actioninput = action()
    if actioninput in ["i", "İ"]:
        i ()
    elif actioninput in ["s", "S"]:
        s ()
    elif actioninput in ["p", "P"]:
        p ()
    else:
        print ("Invalid Action!")

所以我的问题是:

    在def p():中的
  1. ,我想打印已添加到列表中的项目。我试了一些东西,但他们没有工作......

  2. 我不知道怎么做"出售"功能,如何从列表中删除项目并将其值添加到全球黄金?

  3. 我编辑了def s():就像这样,我得到一个错误:

    def s():
        global gold
        sell = input ("What item would you like to sell?")
        if sell == "Apple":
            inventory.remove (Apple)
            gold = gold + 2
        elif sell == "Orange":
            inventory.remove (Orange)
            gold = gold + 7
        elif sell == "Banana":
            inventory.remove (Banana)
            gold = gold + 4
        elif sell == "Grapes":
            inventory.remove (Grapes)
            gold = gold + 5
    
    ValueError: list.remove(x): x not in list
    

3 个答案:

答案 0 :(得分:2)

  1. "在def p():中,我想打印已添加到列表中的项目。"
  2. 最简单的方法是使用中间变量:

    def p ():
        pick = [Apple(), Orange(), Grapes(), Banana()]
        fruit_picked = random.choice(pick)
        inventory.append (fruit_picked)
        print("you picked a", fruit_picked)
    

    您还可以使用indice [-1]获取列表的最后一个元素:

    def p ():
        pick = [Apple(), Orange(), Grapes(), Banana()]
        inventory.append (random.choice(pick))
        print("you picked a", inventory[-1])
    
    1. "如何从列表中删除项目并将其值添加到全球黄金?"
    2. 使用list.pop弹出一个项目,然后使用.value属性执行操作:

      def s():
          global gold #need this in the function that you are modifying the global value
          fruit_sold = inventory.pop() #pop the last item
          gold += fruit_sold.value
      
      1. "如何从列表中选择要删除的特定元素"
      2. 为此,有几种方法,如果不对Fruit类进行修改,您可以遍历列表并检查与输入名称相同的水果:

        def s():
            global gold
            fruit_to_sell = input("what kind of fruit do you want to sell? ")
            for fruit in inventory:
                if fruit.name == fruit_to_sell:
                    gold+=fruit.value
                    inventory.remove(fruit)
                    print("ok, you just sold a(n) {0} for {0.value} gold".format(fruit))
                    return #finish the function
            #if no fruit was found
            print("you don't have any of those kind of fruit \n" + 
                  "(This demo doesn't check for capitalization)")
        

        您收到错误的原因是您尝试从广告资源中删除<​​strong>类,列表中只有Fruit对象,因此不会产生大量的感:

        Apple == Apple() #almost always false, unless you   specifically overloaded __eq__ to make it True.
        

        你可以改变你的Fruit类,这样只要水果是相同的类型(子类),它们就会比较相等:

        class Fruit:
            def __eq__(self,other):
                return type(self) == type(other) 
            ...
        

        那么您的销售可能只是稍微调整以删除任何实例:

        def s():
            global gold
            sell = input ("What item would you like to sell?")
            if sell == "Apple":
                inventory.remove (Apple()) #make an instance here@
                gold = gold + 2
            elif sell == "Orange":
                inventory.remove (Orange())
                ... #you get the point
        

        虽然如果你试图卖苹果但没有,这仍然会引起错误,你可能会更好地检查一下是否有第一个:

        def s():
            global gold
            sell = input ("What item would you like to sell?")
            if sell == "Apple":
                selling = Apple()
            elif sell == "Orange":
                selling = Orange()
            elif sell == "Banana":
                selling = Banana()
            elif sell == "Grapes":
                selling = Grapes()
            if selling in inventory: #make sure you have some of what ever you are selling before trying to sell it!
                inventory.remove(selling)
                gold += int(selling.value.rstrip(" Gold"))
                 # I didn't realize value was a str, this shoddy conversion
                 #  works but is not a very good solution
            else:
                print("you don't have any of those!\n"+
                      "(This demo doesn't check for capitalization)")
        

答案 1 :(得分:0)

使用isinstance()来检测对象所属的类。

保持全局变量不是一个好方法。也许开始构建一个值来传递函数作为一个帐户。

然后在购买之前检查您的余额。 (预算外)等

答案 2 :(得分:0)

list_name[-1]是列表中的最后一项,因此是最近附加的项目。

在您的情况下:inventory[-1]

在sell函数中,您可以使用list_name.remove('element_to_be_removed')删除列表中的元素。

在你的情况下:

fruit_to_remove = inventory[-1]
inventory.remove(fruit_to_remove)

或使用list.pop()。 (根据Tadhg McDonald-Jensen的评论)

相关问题