Reputation: 3849
I have a list of words, for example:
[man, walk, ball]
and I wish to produce their co-occurrences; i.e.:
[('man', 'walk'), ('man', 'ball'), ('walk', 'ball')]
I use the following code:
from itertools import product
my_list = [man, walk, ball]
list(product(my_list, my_list))
which gives me:
[('man', 'man'), ('man', 'walk'), ('man', 'ball'), ('walk', 'man'), ('walk', 'walk'), ('walk', 'ball'), ('ball', 'man'), ('ball', 'walk'), ('ball', 'ball')]
I wonder how to omit duplicate pairs?
Upvotes: 0
Views: 779
Reputation: 923
Try itertools.combinations(iterable, r)
:
>>> import itertools
>>> list(itertools.combinations(['man', 'walk', 'ball'], 2))
[('man', 'walk'), ('man', 'ball'), ('walk', 'ball')]
Upvotes: 6