0

为了从列表 li 中提取所有(可能不连续的)长度为 r 的子列表,我编写了函数

def sublist(li, r):
    output = list()
    if r == 1:
        return [ [element] for element in li ]
    for firstelement in [1,len(li)-r+1]:
        output +=  [ [li[firstelement-1]] + smallerlist for smallerlist in   sublist(li[firstelement:],r-1) ]
    return output

它似乎不起作用:

sage: li = [20, 17, 33, 3001]
sage: sublist(li, 2)
[[20, 17], [20, 33], [20, 3001], [33, 3001]]

请注意,以 17 开头的子列表会被跳过。问题似乎是在递归调用期间计数器firstelement被修改。有没有简单的方法来解决这个问题?

4

1 回答 1

2

嗯,猜猜 - 你想复制组合吗?:

from itertools import combinations
list(combinations(el, 2))
# [(20, 17), (20, 33), (20, 3001), (17, 33), (17, 3001), (33, 3001)]

您可以使用“相当于:”部分帮助编写您自己的代码:

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)
于 2012-10-18T11:07:17.320 回答