Python嵌套循环唯一对 [英] Python Nested Loop unique pairs
问题描述
我正在尝试编写一个嵌套循环,以打印出某个范围内所有可能的唯一对"数字.例如,如果范围是1到3,则唯一对将是:
I'm trying to write a nested loop that prints out all possible "unique pairs" of numbers from a certain range. For example, if the range was from 1 to 3 the unique pairs would be:
(1,2) (1,3) (2,3)
(1,2) (1,3) (2,3)
如果范围是1到4,则唯一对将是:
If the range was from 1 to 4 the unique pairs would be:
(1,2) (1,3) (1,4) (2,3) (2,4) (3,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).但这是一个hack,因为当我将范围更改为1.5时它不起作用.它打印出重复的对,例如(1,5)和(5,1).
which prints out (1, 2), (1, 3),(2, 3). But this is a hack because it doesn't work when I change the range to 1,5. It prints out duplicate pairs such as (1,5) and (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)]
只要您的输入是唯一的,就不会有重复的组合:
As long as your inputs are unique, there will be no repeated combinations:
itertools.combinations(iterable, r)
从输入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嵌套循环唯一对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!