要编写一个代码,将以下顺序添加到burgerlist中的my_order项目:burgerlist的第一个和最后一个元素应该是面包,第二个和前一个最后一个元素应该是蛋黄酱(如果在调用函数时存在于参数中) ),然后是牛肉/鸡肉,然后是蔬菜。 请帮助了解此处的更改
def my_odrer(*g):
ingredients = [['long_bread', 'circle_bread'], ['mayonnaise', 'ketchup'], ['beef', 'chicken'],
['cucumber', 'tomato', 'onion']]
burgerlist = []
for i in g:
if i in ingredients[0]:
burgerlist.insert(0, i)
elif i in ingredients[1]:
burgerlist.insert(1, i)
elif i in ingredients[2]:
burgerlist.append(i)
elif i in ingredients[3]:
burgerlist.append(i)
if burgerlist[1] == 'mayonnaise':
burgerlist.append(burgerlist[1])
burgerlist.append(burgerlist[0])
return burgerlist
print(my_odrer('circle_bread', 'beef', 'tomato', 'mayonnaise', 'ketchup'))
输出为:['circle_bread', 'ketchup', 'mayonnaise', 'beef', 'tomato', 'circle_bread']
但是我想得到:['circle_bread', 'mayonnaise', 'ketchup', 'beef', 'tomato','mayonnaise', 'circle_bread']
答案 0 :(得分:0)
创建3个列表,其中包含应该在开头,中间和结尾处的成分。然后将它们连接起来以产生最终结果。
def my_odrer(*g):
breads = {'long_bread', 'circle_bread'}
condiments = {'ketchup'} # mayonnaise not included, since it's handled specially
meats = {'beef', 'chicken'}
vegetables = {'cucumber', 'tomato', 'onion'}
beginning = []
middle = []
end = []
for item in g:
if item in breads:
beginning.append(item)
end.append(item)
if "mayonnaise" in g:
beginning.append("mayonnaise")
end.insert(-1, "mayonnaise")
for item in g:
if item in condiments:
middle.append(item)
for item in g:
if item in meats:
middle.append(item)
for item in g:
if item in vegetables:
middle.append(item)
return beginning + middle + end
答案 1 :(得分:0)
在我在您的最终if语句中添加了附加条件之后,此方法才起作用。
def my_odrer(*g):
ingredients = [['long_bread', 'circle_bread'], ['mayonnaise', 'ketchup'], ['beef', 'chicken'],
['cucumber', 'tomato', 'onion']]
burgerlist = []
for i in g:
if i in ingredients[0]:
burgerlist.insert(0, i)
elif i in ingredients[1]:
burgerlist.insert(1, i)
elif i in ingredients[2]:
burgerlist.append(i)
elif i in ingredients[3]:
burgerlist.append(i)
if burgerlist[1] == 'mayonnaise':
burgerlist.append(burgerlist[1])
elif burgerlist[2] == 'mayonnaise':
burgerlist[1], burgerlist[2] = burgerlist[2], burgerlist[1]
burgerlist.append(burgerlist[1])
burgerlist.append(burgerlist[0])
return burgerlist