【问题标题】:Avoid duplicates in nested loop python避免嵌套循环python中的重复
【发布时间】:2020-05-07 15:57:56
【问题描述】:

所以我有嵌套循环和数组 [[0, 1], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4]]

for x in string_list:
        for y in string_list:
            print(x,y)

为我提供输出

[0, 1] [0, 1]
[0, 1] [0, 1, 2, 3, 4, 5, 6]
[0, 1] [0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5, 6] [0, 1]
[0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4]
[0, 1, 2, 3, 4] [0, 1]
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4]

但是我有很多重复的对,我做到了:

for x in range(0, len(string_list)):
      for y in range(x+1, len(string_list)): 
          print(x,y, string_list)

但它仅适用于 2 位数字对。 所以我想要的是:

[0, 1] [0, 1]
[0, 1] [0, 1, 2, 3, 4, 5, 6] 
[0, 1] [0, 1, 2, 3, 4]
**[0, 1, 2, 3, 4, 5, 6] [0, 1]** // avoid to output that pair cause we had that one 
[0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4]
[0, 1, 2, 3, 4] [0, 1]
**[0, 1, 2, 3, 4] [0, 1, 2, 3, 4, 5, 6]** // avoid to output that pair cause we had that one 
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4]

不使用 itertools 可以吗? 谢谢!

【问题讨论】:

  • 您是否有不想使用itertools的原因?

标签: python arrays python-3.x


【解决方案1】:
for k, x in enumerate(string_list):
    for y in string_list[k:]:
        print(x,y)

【讨论】:

    【解决方案2】:

    你可以使用itertools.combinations:

    for x, y in it.combinations(string_list, 2):
        # process x, y
    

    【讨论】:

    • 他不想用itertools
    • @DanielWalker 这不是一个合理的论点。存在标准库以供使用。它可以轻松使用,功能只需导入一次。
    • 谢谢,@DanielWalker。学到了一些新东西。 :)
    【解决方案3】:

    显然使用itertools.combinations 是理想的,但既然你说你不想使用itertools,你可以使用集合推导来构建一组独特的组合(你必须将列表转换为元组才能使它们可散列),然后根据需要将它们转换回列表:

    [list(list(t) for t in f) for f in {
        frozenset((tuple(x), tuple(y))) for y in string_list for x in string_list
    }]
    

    【讨论】:

    • 这给出了与 OP 他的输出完全相同的输出。
    • 需要在其中增加一层设置,已修复。 :D
    • 我现在的头痛可能需要一套冷冻冰块。 :)
    【解决方案4】:

    您可以在内部循环中放置continue 语句以跳过重复项:

     for x in string_list:
         for y in string_list:
             if x == y:
                 continue
             print(x,y)
    

    【讨论】:

    • 是的,但它只会删除:[0, 1] [0, 1], [0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3 , 4, 5, 6], [0, 1, 2, 3, 4] [0, 1, 2, 3, 4], 对吗?不是我想要的
    猜你喜欢
    • 1970-01-01
    • 2017-08-27
    • 2017-11-11
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 2017-09-20
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多