python - 避免在嵌套循环python中重复

标签 python arrays

所以我有嵌套循环和数组 [[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 可以吗? 谢谢!

最佳答案

for k, x in enumerate(string_list):
    for y in string_list[k:]:
        print(x,y)

关于python - 避免在嵌套循环python中重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61662286/

相关文章:

c++ - 如何将 vector<string> 转换为 char* arr[]?

javascript - 将字符串按照指定长度分割成数组

c++ - 指向基类数组的指针,用派生类填充

java - 我如何制作多种模式以及程序检测其是双峰还是三峰

python - 如何从 StringIO 对象中删除第一个字符?

python - 如何编写python表达式来过滤掉某些字符串

python - 验证文件未被修改

python - asyncio.run 运行时错误 : Event loop is closed

arrays - swift - corebluetooth 写入 2 个字节

php - 获取退出代码(一)在Symfony中使用Process的Error输出中的错误和输出