Itertools 产品不重复重复
Posted
技术标签:
【中文标题】Itertools 产品不重复重复【英文标题】:Itertools product without repeating duplicates 【发布时间】:2015-06-01 14:08:25 【问题描述】: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']
如何:
-
避免在一个句子中重复同名(印度和印度)
只生成一个组合(印度和澳大利亚或澳大利亚和印度)
http://pythonfiddle.com/product-without-matching-duplicates
【问题讨论】:
【参考方案1】:你应该像这样使用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']
【讨论】:
哪一个会更快?组合还是枚举? @emaillenincombinations
更快但不是很多:repl.it/fu7 但是,没有理由不使用组合。以上是关于Itertools 产品不重复重复的主要内容,如果未能解决你的问题,请参考以下文章
当重复次数高于 9 时,itertools.permutations 不起作用
itertools.product的Numpy等价物[重复]