使用小于运算符从列表中删除项目

时间:2015-09-25 05:30:38

标签: python string list

我正在为一个类创建一个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。 我不能把我的大脑包裹起来所以任何帮助都会很棒。

此外,欢迎任何其他改进我的代码的建议!

1 个答案:

答案 0 :(得分: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)

你可以尝试类似的东西。