Python 嵌套循环唯一对
Python Nested Loop unique pairs
我正在尝试编写一个嵌套循环,打印出特定范围内所有可能的 "unique pairs" 数字。例如,如果范围是从 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)。
您可能正在寻找这样的东西:
n = 4
x = [(i,j) for i in range(1,n+1) for j in range(i+1, n+1)]
print x
干杯,
亚历克斯
for i in range(1,4):
for j in range(i+1,4): # <-- the key is to make j start at i+1
print (i,j)
>>> 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.
您可以使用 itertools.combinations
:
>>> from itertools import combinations
>>> print list(combinations(range(1,4), 2))
[(1, 2), (1, 3), (2, 3)]
参见 itertools 模块。
也许你想要的是
list(itertools.combinations(range(1,4),2)) == [(1, 2), (1, 3), (2, 3)]
我正在尝试编写一个嵌套循环,打印出特定范围内所有可能的 "unique pairs" 数字。例如,如果范围是从 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)。
您可能正在寻找这样的东西:
n = 4
x = [(i,j) for i in range(1,n+1) for j in range(i+1, n+1)]
print x
干杯, 亚历克斯
for i in range(1,4):
for j in range(i+1,4): # <-- the key is to make j start at i+1
print (i,j)
>>> 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.
您可以使用 itertools.combinations
:
>>> from itertools import combinations
>>> print list(combinations(range(1,4), 2))
[(1, 2), (1, 3), (2, 3)]
参见 itertools 模块。
也许你想要的是
list(itertools.combinations(range(1,4),2)) == [(1, 2), (1, 3), (2, 3)]