我有一个单词列表,例如:
[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')]
我想知道如何省略重复对?
答案 0 :(得分:4)
尝试itertools.combinations(iterable, r)
:
>>> import itertools
>>> list(itertools.combinations(['man', 'walk', 'ball'], 2))
[('man', 'walk'), ('man', 'ball'), ('walk', 'ball')]