[英]Print last item added to list
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():中,我要打印已添加到列表中的項目。 我嘗試了一些東西,但是沒有用...
我不知道如何執行“出售”功能,如何從列表中刪除某項並將其值添加到全球黃金中?
我編輯了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
def p():
,我要打印已添加到列表中的項目。” 最簡單的方法是只使用一個中間變量:
def p ():
pick = [Apple(), Orange(), Grapes(), Banana()]
fruit_picked = random.choice(pick)
inventory.append (fruit_picked)
print("you picked a", fruit_picked)
您還可以使用索引[-1]
獲得列表的最后一個元素:
def p ():
pick = [Apple(), Orange(), Grapes(), Banana()]
inventory.append (random.choice(pick))
print("you picked a", inventory[-1])
使用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
為此,有幾種方法,無需對您的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)")
出現錯誤的原因是因為您試圖從清單中刪除該類 ,所以列表中僅存在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)")
使用isinstance()來檢測對象屬於哪個類。
保持全局變量不是一個好方法。 也許開始建立一個值以將功能作為一個帳戶傳遞出去。
然后在購買前檢查余額。 (預算外)等
list_name[-1]
是列表中的最后一項,因此是最近添加的一項。
在您的情況下:廣告inventory[-1]
在賣方功能中,您可以使用list_name.remove('element_to_be_removed')
刪除列表中的元素。
在您的情況下:
fruit_to_remove = inventory[-1]
inventory.remove(fruit_to_remove)
或使用list.pop()
。 (根據Tadhg McDonald-Jensen的評論)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.