我正在尝试编写一个嵌套循环,打印出特定范围内所有可能的“唯一对”数字。例如,如果范围是从 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)。
最佳答案
>>> 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 inputiterable
.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/