简体   繁体   中英

Deleting items from a list with a less than operator

I am working on a program for a class which has us build a craigslist type of program.

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

Fairly easy to read what's going on here but I am missing a crucial part which is deleting entries from myStr. I tried using a for loop but it did not work. What I need it to do is delete the first entry that meets this criteria. if maximum > itemCost then delete the first item in the list . I can't wrap my brain around it so any help would be great.

Also, any other advice to improve my code is welcome!

You could try something extracting the list of items whose cost is greater than maximum and then removing those items from your list. List comprehension is great at it.

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)

You could try with something like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM