Python 项目赢得';是否从列表中删除带有变量的项?
我正在写一个程序,在这个程序中,我需要根据个人搜索结果从列表中删除产品。 下面是我的代码:Python 项目赢得';是否从列表中删除带有变量的项?,python,list,Python,List,我正在写一个程序,在这个程序中,我需要根据个人搜索结果从列表中删除产品。 下面是我的代码: list = [['bike', 50], ['truck', 1000], ['microwave', 10]] while True: print "----------------------" print "Welcome to Craigslist" print "Would you like to:" print "1. Add an item."
list = [['bike', 50], ['truck', 1000], ['microwave', 10]]
while True:
print "----------------------"
print "Welcome to Craigslist"
print "Would you like to:"
print "1. Add an item."
print "2. Find an item."
print "3. Print the message board."
print "4. Quit."
choice = eval(raw_input("Please make a selection."))
print "-----------------------"
#i took out choice 1 because the problem isn't in choice 1
if choice == 2:
print "What are you looking for? A bike, microwave, dresser, truck or chicken?"
itemType = raw_input ("Enter the item type- b, m, d, t, c,:")
print list
if itemType == "m":
itemCost = eval(raw_input("Enter the maximum item cost:"))
list.remove[('microwave',itemCost)]
print list
elif itemType == "d":
itemCost = eval(raw_input("Enter the maximum item cost:"))
list.remove('dresser',itemCost)
print list
elif itemType == "b":
itemCost = eval(raw_input("Enter the maximum item cost:"))
list.remove[('bike' ,itemCost)]
print list
elif itemType == "t":
itemCost = eval(raw_input("Enter the maximum item cost:"))
list.remove[('truck',itemCost)]
print list
elif itemType == "c":
itemCost = eval(raw_input("Enter the maximum item cost:"))
list.remove[('chicken',itemCost)]
print list
if choice == 3:
print "These are the items for sale on Craigslist."
print list
if choice == 4:
quit ("Bye!")
else:
quit ("Sorry, that's not an option on the menu.")
当我尝试根据项目名称和输入价格从列表中删除项目时,会出现以下错误:
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
我之前做过这项工作,当我输入价格50
时,它很容易从列表中删除bike
,我尝试过完全重写行,切换括号和括号,使bike
和bikePrice
等于一个变量,然后删除该变量-我似乎无法让它工作。如果能为我的业余编码大脑提供任何信息,我将不胜感激 建议:
我想如果你做了这些修正,代码会做你想做的事情。希望有帮助 与您的问题无关:请使用
int
或ast.literal\u eval
而不是eval
。您的列表在您的代码中是否实际称为list
?另外,.remove[('bike',itemCost)]
根本不是调用函数的方式。您使用的是list
作为变量名,隐藏pythonlist
这不是一个好主意,您还试图索引方法引用,它将是my_list.remove(['chicken',itemCost])
您需要()在您的删除呼叫中,列表是列表而不是元组列表,('chicken',50)
是元组,['chicken',50]
是列表非常感谢!第二个建议奏效了