2016-10-28 193 views
-1

我正在爲用戶建立購物清單的程序。它應該 重複詢問用戶的項目,直到他們輸入'結束',然後它應該打印列表。如果用戶已經添加了一個項目,那麼下次應該忽略它。我遇到了應該忽略重複的最後部分的問題。我還需要使用'繼續',但不知道如何實現我的代碼。相同的輸入兩次不要輸入兩次

shoppingListVar = [] 
while True: 
    item = input("Enter your Item to the List: ") 
    shoppingListVar.append(item) 
    if item in item: 
     print("you already got this item in the list") 
    if item == "end": 
     break 
print ("The following elements are in your shopping list:") 
print (shoppingListVar) 
+0

你靠近......你需要檢查,如果該項目在列表*之前*追加它,然後將'繼續'添加到該'if語句... –

+0

嗯我仍然不能把它正確的,'如果項目中的項目:'是寫得很好的代碼? – user3077730

+0

我認爲你的意思是,如果項目在shoppingListVar而不是項目在項目中 –

回答

0

它應該是if item in shoppingListVar:

shoppingListVar = [] 
while True: 
    item = input("Enter your Item to the List: ") 
    if item == "end": 
     break 

    if item in shoppingListVar: 
     print("you already got this item in the list") 
     continue 

    shoppingListVar.append(item) 

print ("The following elements are in your shopping list:") 
print (shoppingListVar) 

此代碼檢查的定點值(「結束」)第一附加新項到列表中,如果它不是已存在於其中之前。

如果購物清單的順序無關緊要,或者您打算對其進行排序,則可以使用set而不是list。這會照顧重複的,你會不會需要檢查對他們來說,只是使用shopping_list.add(item)(與shopping_list = set()初始化)

shopping_list = set() 
while True: 
    item = input("Enter your Item to the List: ") 
    if item == "end": 
     break 
    shopping_list.add(item) 

print("The following elements are in your shopping list:") 
print(shopping_list) 
+0

我不得不使用該練習練習的列表,但我一直銘記在心,謝謝 – user3077730

+0

@ user3077730:夠公平的。 – mhawke

+0

@ user3077730:如果需要使用「continue」,則只要檢測到重複條目,就可以添加該條目。查看更新的答案。 – mhawke

0

你會用更好的,如果 - elif的 - else結構在你的代碼來處理3個不同的預期條件

而且你需要更改if item in item:if item in shoppingListVar:

shoppingListVar = [] 
while True: 
    item = input("Enter your Item to the List: ") 
    if item in shoppingListVar: 
     print("you already got this item in the list") 
    elif item == "end": 
     break 
    else: 
     shoppingListVar.append(item) 
print ("The following elements are in your shopping list:") 
print (shoppingListVar) 
+0

ohh我看到我嘗試過如果項目在shoppingListVar中但我有一個if-elif-else結構所以也許這就是爲什麼它沒有工作。有沒有機會發出「繼續」聲明?我不知道這是如何工作的 – user3077730