2011-04-20 96 views

回答

13

请参阅itertools.combinations的文档。没有此功能的等效代码:http://www.python.org/download/

尝试下载最新版本:

def combinations(iterable, r): 
    # combinations('ABCD', 2) --> AB AC AD BC BD CD 
    # combinations(range(4), 3) --> 012 013 023 123 
    pool = tuple(iterable) 
    n = len(pool) 
    if r > n: 
     return 
    indices = range(r) 
    yield tuple(pool[i] for i in indices) 
    while True: 
     for i in reversed(range(r)): 
      if indices[i] != i + n - r: 
       break 
     else: 
      return 
     indices[i] += 1 
     for j in range(i+1, r): 
      indices[j] = indices[j-1] + 1 
     yield tuple(pool[i] for i in indices) 
+0

这实际上是如何工作的?我试图理解+我错过了一些东西。 'indices'数组告诉我使用了哪些池的元素,但我似乎无法弄清楚它是如何产生不包含重复的索引集的。 – 2015-03-13 00:26:22

+1

@JasonS,有几点:首先,从示例中注意到,算法生成的具有'indices'的元组总是被排序(特别是'indices [i] user3780389 2017-03-08 17:21:42

+0

@JasonS我对else:return语句感到困惑。那里有什么缩进。什么时候执行,如果对应于这个else? – MaPy 2017-10-02 16:18:41

相关问题