sampling a fixed number of unique pairs from a population

Viewed 31

I have a sample of n elements. I want to sub-sample m unique pairs from n. Is there a simple off-the-self method to do this in python ?

For example, if n = [1,2,3,4,5,6,7] and m = 3, one such sample will be [(1,2),(3,4),(5,6)]

2 Answers

The random module has a sample function which will pick n unique items from a collection. You can then pair them up to create your desired output:

import random
import itertools

data = [1,2,3,4,5,6,7,8,9,10]
m = 3

def pairwise(iterable):
    # from the itertools cookbook: https://docs.python.org/3/library/itertools.html#itertools-recipes
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

chosen = random.sample(data, m * 2)
result = pairwise(chosen)

Depending on what you mean precisely with 'random', the answer will differ!

For uniform sampling of unique pairs, assuming all elements of your list are distinct:

import itertools, random
n, m = [1,2,3,4,5,6,7], 3
x = random.sample( list(itertools.permutations(n,2)), m)
print(x) #e.g. [(1,2),(3,4),(5,6)] 
Related