2016-04-14 71 views
0

我有单词的列表,例如:独特共现对

[man, walk, ball] 

,我希望生产他们共同出现;即:

[('man', 'walk'), ('man', 'ball'), ('walk', 'ball')] 

我使用下面的代码:

from itertools import product 
my_list = [man, walk, ball] 
list(product(my_list, my_list)) 

这给了我:

[('man', 'man'), ('man', 'walk'), ('man', 'ball'), ('walk', 'man'), ('walk', 'walk'), ('walk', 'ball'), ('ball', 'man'), ('ball', 'walk'), ('ball', 'ball')] 

不知如何省略重复的对?

+1

你_have_使用'product'?为什么不使用“组合”? –

+2

'list(combinations(my_list,r = 2))' – zezollo

+0

适用于'组合“。 – Andrej

回答

4

尝试itertools.combinations(iterable, r)

>>> import itertools 
>>> list(itertools.combinations(['man', 'walk', 'ball'], 2)) 
[('man', 'walk'), ('man', 'ball'), ('walk', 'ball')]