【问题标题】:Print a list of two outputs with no duplicates or similar duos打印两个输出的列表,没有重复或类似的二重奏
【发布时间】:2021-10-04 10:41:12
【问题描述】:

我已经为我的脚本寻找了一个解决方案,但没有成功。

我正在尝试打印给定列表中所有可能的二重奏。除了不打印重复项,例如 (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) 不会被打印。

【问题讨论】:

标签: python list for-loop duplicates


【解决方案1】:

您可以使用itertools.combinations

import itertools
FLAVORS = [
    "Banana",
    "Chocolate",
    "Lemon",
    "Pistachio",
    "Raspberry",
    "Strawberry",
    "Vanilla",
]
x=list(itertools.combinations(FLAVORS,2))
print(x)

【讨论】:

  • 谢谢,效果很好。我一直在寻找 for 循环的方式,来练习 for 循环,但我不会接受这个。再次感谢。
【解决方案2】:

类似的东西?

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

【讨论】:

  • 谢谢,就像上面的代码一样,这正是我想要的 :) 所以谢谢。
【解决方案3】:

解决办法

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=",")

【讨论】:

  • 谢谢,这正是我想要的。你能解释一下for循环代码吗?就知道不打印重复和二重奏而言,这是如何工作的?
  • 啊,我没有。我用pythontutor.com/visualize。我之前试过这个,它打印出的是物品的编号而不是物品。我看到你需要把 FLAVOURS[i] 打印出来:) 谢谢谢谢谢谢
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 2021-02-06
  • 1970-01-01
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多