[英]How do I add multiple items to a List in Python?
所以我有一個運行 Craigslist 類型網站的代碼,理論上。 這是代碼。
#Problem 4
choice = ()
while choice != 4:
print "1. Add an item."
print "2. Find an item."
print "3. Print the message board."
print "4. Quit."
choice = input("Enter your selection:")
if choice == 4:
break
#Add an item
if choice == 1:
b = "bike"
m = "microwave"
d = "dresser"
t = "truck"
c = "chicken"
itemType = raw_input("Enter the item type-b,m,d,t,c:")
itemCost = input("Enter the item cost:")
List = []
List.extend([itemType])
List.extend([itemCost])
print List
用戶應該能夠選擇 1 輸入他們的項目,再次按 1 並輸入更多項目。 如何在不覆蓋先前輸入的情況下保存列表?
首先,不要使用List
作為變量名。 它是 Python 中的內置類型。
您覆蓋先前輸入的原因是因為每次用戶輸入 1 時您都在定義一個新列表。在條件語句的范圍之外定義您的列表。
#Problem 4
itemList = []
choice = ()
while choice != 4:
print "1. Add an item."
print "2. Find an item."
print "3. Print the message board."
print "4. Quit."
choice = input("Enter your selection:")
if choice == 4:
break
#Add an item
if choice == 1:
b = "bike"
m = "microwave"
d = "dresser"
t = "truck"
c = "chicken"
itemType = raw_input("Enter the item type-b,m,d,t,c:")
itemCost = input("Enter the item cost:")
itemList.append((itemType, itemCost))
print itemList
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.