【发布时间】:2020-11-10 10:45:43
【问题描述】:
您在一家餐厅工作,他们要求您生成冰糕菜单。
提供一个脚本,打印给定口味列表中所有可能的冰糕二重奏。
不要打印两次相同口味的食谱(没有“巧克力巧克力”),也不要打印两次相同的食谱(如果您打印“香草巧克力”,请不要打印“巧克力香草”,反之亦然- 反之)。
口味是:
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
>我的代码在这里:
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
for i in FLAVORS:
if len(FLAVORS) >= 2:
for g in FLAVORS:
if g==i:
continue
else:
print(f"{i}, {g}")
FLAVORS.remove(g)
我得到的结果:
Banana, Chocolate
Banana, Lemon
Banana, Pistachio
Banana, Raspberry
Banana, Strawberry
Banana, Vanilla
Chocolate, Banana
Chocolate, Lemon
Chocolate, Pistachio
Chocolate, Raspberry
Chocolate, Strawberry
Lemon, Banana
Lemon, Chocolate
Lemon, Pistachio
Lemon, Raspberry
Pistachio, Banana
Pistachio, Chocolate
Pistachio, Lemon
问题是: 为什么不推荐开心果、覆盆子(或覆盆子、开心果)?
【问题讨论】:
-
因为您在遍历列表时删除了条目。在PythonTutor 上尝试以了解问题所在。
标签: python python-3.x permutation