How can I obtain all unique pairs in a list, allowing for repeats?
E.g. for the list [20, 20, 19]
I'd like (20, 20)
and (20, 19)
.
And for [20, 20, 19, 19, 18]
I'd like (20, 20)
, (20, 19)
, (20, 18)
, (19, 19)
and (19, 18)
I don't really mind what object is returned (list, tuple, dict, set etc) as long as I can then iterate over each pair, and extract both numbers
CodePudding user response:
You can use itertools.combinations
in a set comprehension:
>>> from itertools import combinations
>>> lst_1 = [20, 20, 19]
>>> {comb for comb in combinations(lst_1, r=2)}
{(20, 19), (20, 20)}
>>> lst_2 = [20, 20, 19, 19, 18]
>>> {comb for comb in combinations(lst_2, r=2)}
{(20, 20), (19, 19), (20, 19), (19, 18), (20, 18)}
Or just cast into a set directly:
>>> set(combinations(lst_1, r=2))
{(20, 19), (20, 20)}
>>> set(combinations(lst_2, r=2))
{(20, 20), (19, 19), (20, 19), (19, 18), (20, 18)}
CodePudding user response:
You can use a double for-loop where in each iteration, the previous element is removed. I think this solution would be faster than itertools.combinations
method especially if the list is large, since it doesn't have to find all combinations first.
def get_pairs(l):
out = []
for i in l:
l.remove(i)
for j in l:
if (i,j) in out or (j,i) in out:
continue
else:
out.append((i,j))
return out
Output:
>>> get_pairs([20, 20, 19, 19, 18])
[(20, 20), (20, 19), (20, 18), (19, 19), (19, 18)]