Python 嵌套循环唯一对

标签 python nested-loops

我正在尝试编写一个嵌套循环,打印出特定范围内所有可能的“唯一对”数字。例如,如果范围是从 1 到 3,唯一对将是:

(1,2) (1,3) (2,3)

如果范围是从 1 到 4,唯一对将是:

(1,2) (1,3) (1,4) (2,3) (2,4) (3,4)

这是我为 1 到 3 做的:

for i in range(1,4):
    for j in range(2,4):
        if (i != j & j != (i-1)):
            print (i,j)

打印出 (1, 2), (1, 3),(2, 3)。但这是一个技巧,因为当我将范围更改为 1,5 时它不起作用。它打印出重复的对,例如 (1,5) 和 (5,1)。

最佳答案

使用itertools.combinations() :

>>> import itertools
>>> print list(itertools.combinations(range(1, 5), r=2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

只要你的输入是唯一的,就不会出现重复的组合:

itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination.

关于Python 嵌套循环唯一对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29324025/

相关文章:

python - 如何用matplotlib控制彩色图像渲染?

java - 为什么我收到 "Exception in thread "main"java.lang.NumberFormat : null. . ."after clicking the "cancel"按钮?

java - 石头剪刀布 Java 游戏

java - 嵌套的 For 循环给出不正确的输出

python - 在 Python 中更新嵌套字典中的值

python - 如何从由字符串、元组和列表组成的列表中创建平面列表?

python - 规范化/标准化 numpy recarray

python - Django 迁移 django.db.utils.OperationalError : no such table:

c++ - C++ 中的嵌套循环和矩阵

python - mac 上 python 子进程中的 pdflatex