Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Thursday, May 3, 2012

Itertools combinations method explained

Itertools combinations returns r length subsequences of elements from the input iterable.
from itertools import combinations

persons = ['Adam', 'Liam', 'Bruce', 'Kate', 'Demi']

#generate list of all possible pairs
print list(combinations(persons,2))

[('Adam', 'Liam'), ('Adam', 'Bruce'), ('Adam', 'Kate'), ('Adam', 'Demi'), 
('Liam', 'Bruce'), ('Liam', 'Kate'), ('Liam', 'Demi'), ('Bruce', 'Kate'), 
('Bruce', 'Demi'), ('Kate', 'Demi')]

No comments:

Post a Comment