2015-09-25 20 views
0

我正在爲我們構建craigslist類型的程序的類程序工作。使用少於運算符從列表中刪除項目

myStr=[] 
b = "bike" 
ans = True 
while ans: 
    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 == 1: 
     itemType = raw_input("Enter the item type-b,m,d,t,c: ") 
     itemCost = input("Enter the item cost: ") 
     myStr.append([itemType,itemCost]) 
    if choice == 2: 
     itemType = raw_input("Enter the item type-b,m,d,t,c: ") 
     maximum = input("Enter the maximum item cost: ") 
     print maximum 
    if choice == 3: 
     print myStr 
    if choice == 4: 
     break 

相當容易閱讀這裏發生了什麼,但我缺少一個關鍵部分是從myStr中刪除條目。我嘗試使用for循環,但它不起作用。我需要做的是刪除符合此條件的第一個條目。 if maximum > itemCost then delete the first item in the list。 我無法把我的大腦包裹起來,所以任何幫助都會很棒。

此外,任何其他建議,以改善我的代碼是值得歡迎的!

+3

有一些方法可以從列表中刪除,但它們基本上很難看,因爲列表對於這類問題並不是很好的數據結構。考慮使用字典。 – Julien

+1

代碼審查請參閱[codereview.se]。 –

+1

寫一些新代碼只是爲了試驗你在兩三行代碼中試圖達到的目標。那麼你的問題可能是關於單個問題。 –

回答

0

您可以嘗試提取成本大於最大值的項目列表,然後從列表中刪除這些項目。列表理解很棒。

max_cost = 3 
myStr = [['Item1', 2], ['Item2', 3], ['Item3', 4]] 
to_remove = [item for item in myStr if item[1] > max_cost] 
for item in to_remove: 
    myStr.remove(item) 

你可以嘗試用類似的東西。