打印两个输出的列表,没有重复或类似的二重奏
Print a list of two outputs with no duplicates or similar duos
我四处寻找脚本的解决方案,但一无所获。
我正在尝试打印给定列表中所有可能的二重奏。除了,不打印重复项,例如 (a, a)。并且不打印组合两次,例如如果 (a, b) 已被打印,则 (b, a) 将不会被打印。
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
for i in FLAVORS:
for j in FLAVORS:
if (i != j) :
print(i, j, sep=", ")
我设法不打印重复项,例如 (a, a)。但是,我坚持如何只打印一次组合,所以如果 (a, b) 被打印, (b, a) 就不会被打印。
import itertools
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
x=list(itertools.combinations(FLAVORS,2))
print(x)
类似的东西?
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
]
n = len(FLAVORS)
for i in range(n):
for j in range(i+1, n):
print(FLAVORS[i], FLAVORS[j], sep=", ")
Banana, Chocolate
Banana, Lemon
Chocolate, Lemon
这是解决方案
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
for i in range(len(FLAVORS)):
for j in range(i+1,len(FLAVORS)):
print(FLAVORS[i],FLAVORS[j],sep=",")
我四处寻找脚本的解决方案,但一无所获。
我正在尝试打印给定列表中所有可能的二重奏。除了,不打印重复项,例如 (a, a)。并且不打印组合两次,例如如果 (a, b) 已被打印,则 (b, a) 将不会被打印。
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
for i in FLAVORS:
for j in FLAVORS:
if (i != j) :
print(i, j, sep=", ")
我设法不打印重复项,例如 (a, a)。但是,我坚持如何只打印一次组合,所以如果 (a, b) 被打印, (b, a) 就不会被打印。
import itertools
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
x=list(itertools.combinations(FLAVORS,2))
print(x)
类似的东西?
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
]
n = len(FLAVORS)
for i in range(n):
for j in range(i+1, n):
print(FLAVORS[i], FLAVORS[j], sep=", ")
Banana, Chocolate
Banana, Lemon
Chocolate, Lemon
这是解决方案
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
for i in range(len(FLAVORS)):
for j in range(i+1,len(FLAVORS)):
print(FLAVORS[i],FLAVORS[j],sep=",")