【问题标题】:Print Sobert has duplicate print打印 Sobert 有重复打印
【发布时间】:2021-09-05 01:16:51
【问题描述】:

好的,我已经包含了我写的代码,当它打印我得到的列表时:你给香蕉,巧克力对两次(一次是香蕉,巧克力,一次是巧克力,香蕉)。我确实找到了没有这个问题的代码,但我的问题是我不明白它是如何解决违背目的的问题。

我的代码:

FLAVORS = [
    "Banana",
    "Chocolate",
    "Lemon",
    "Pistachio",
    "Raspberry",
    "Strawberry",
    "Vanilla",
]

for x in FLAVORS:
    for y in FLAVORS:
        if x != y:
            print(x + ", " + y)

有效但我不明白的代码:

FLAVORS = [
    "Banana",
    "Chocolate",
    "Lemon",
    "Pistachio",
    "Raspberry",
    "Strawberry",
    "Vanilla",
]

for flavor_one in FLAVORS:
    for flavor_two in range(FLAVORS.index(flavor_one)+1,len(FLAVORS)):
        print(flavor_one + ", " + FLAVORS[flavor_two])

【问题讨论】:

    标签: python duplicates combinations


    【解决方案1】:

    好的,如果我理解您要求您的代码工作的内容,您可以在下面的代码中进行编辑。因此,代码中发生的事情是您正在检查 FLAVORS 的范围,然后将名为 FLAVORS 的列表附加到索引中。您将索引指向“x”并告诉它增加 1 然后它检查 FLAVORS 的长度,这是代码确认您没有得到巧克力香蕉和香蕉巧克力的地方。这一切都发生在range(FLAVORS.index(x)+1,len(FLAVORS)): 中,从那时起您将打印第一种风味 (x),第二种风味。 FLAVORS[y] 指向您将 FLAVORS 转换为索引时的上一行。

    另外,这里是 index 的语法,因为我假设这是让你失望的原因。

    语法 list.index(elmnt)

    for x in FLAVORS:
        for y in range(FLAVORS.index(x)+1,len(FLAVORS)):
            if x != y:
                print(x + ", " + FLAVORS[y])
    

    【讨论】:

      【解决方案2】:

      事实上,在 first code 中,您打印了所有 xy 不同的对,因此您得到了重复的对。 但实际上在second code 中,您尝试打印数组中的所有组合,请参阅此示例(ref):

      要获取数组元素的所有组合,您可以使用 second code 或使用 itertools.combinations(array, size_pair),如下所示:

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

      输出:

      [('Banana', 'Chocolate'), 
      ('Banana', 'Lemon'), 
      ('Banana', 'Pistachio'), 
      ('Banana', 'Raspberry'), 
      ('Banana', 'Strawberry'), 
      ('Banana', 'Vanilla'), 
      ('Chocolate', 'Lemon'), 
      ('Chocolate', 'Pistachio'), 
      ('Chocolate', 'Raspberry'), 
      ('Chocolate', 'Strawberry'), 
      ('Chocolate', 'Vanilla'), 
      ('Lemon', 'Pistachio'), 
      ('Lemon', 'Raspberry'), 
      ('Lemon', 'Strawberry'), 
      ('Lemon', 'Vanilla'), 
      ('Pistachio', 'Raspberry'), 
      ('Pistachio', 'Strawberry'), 
      ('Pistachio', 'Vanilla'), 
      ('Raspberry', 'Strawberry'), 
      ('Raspberry', 'Vanilla'), 
      ('Strawberry', 'Vanilla')]
      

      【讨论】:

        猜你喜欢
        • 2012-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-04
        • 2016-10-03
        • 1970-01-01
        相关资源
        最近更新 更多