Itertools 乘积不重复
Itertools product without repeating duplicates
from itertools import product
teams = ['india', 'australia', 'new zealand']
word_and = ['and']
tmp = '%s %s %s'
items = [teams, word_and, teams]
print(list(tmp % a for a in list(product(*items))))
打印:
['india and india',
'india and australia',
'india and new zealand',
'australia and india',
'australia and australia',
'australia and new zealand',
'new zealand and india',
'new zealand and australia',
'new zealand and new zealand']
如何:
- 避免在一个句子中重复相同的名字(印度和印度)
- 只生成一种组合(印度和澳大利亚或澳大利亚和印度)
你应该这样使用itertools.combinations
>>> from itertools import combinations
>>> teams = ['india', 'australia', 'new zealand']
>>> [" and ".join(items) for items in combinations(teams, r=2)]
['india and australia', 'india and new zealand', 'australia and new zealand']
但是对于这个简单的例子,你可以运行两个循环,像这样
>>> ["%s and %s" % (t1, t2) for i, t1 in enumerate(teams) for t2 in teams[i + 1:]]
['india and australia', 'india and new zealand', 'australia and new zealand']
from itertools import product
teams = ['india', 'australia', 'new zealand']
word_and = ['and']
tmp = '%s %s %s'
items = [teams, word_and, teams]
print(list(tmp % a for a in list(product(*items))))
打印:
['india and india',
'india and australia',
'india and new zealand',
'australia and india',
'australia and australia',
'australia and new zealand',
'new zealand and india',
'new zealand and australia',
'new zealand and new zealand']
如何:
- 避免在一个句子中重复相同的名字(印度和印度)
- 只生成一种组合(印度和澳大利亚或澳大利亚和印度)
你应该这样使用itertools.combinations
>>> from itertools import combinations
>>> teams = ['india', 'australia', 'new zealand']
>>> [" and ".join(items) for items in combinations(teams, r=2)]
['india and australia', 'india and new zealand', 'australia and new zealand']
但是对于这个简单的例子,你可以运行两个循环,像这样
>>> ["%s and %s" % (t1, t2) for i, t1 in enumerate(teams) for t2 in teams[i + 1:]]
['india and australia', 'india and new zealand', 'australia and new zealand']