如何在没有itertools.combinations的情况下在Python中生成列表的增加排列

问题描述 投票:0回答:1

如何在没有itertools.combinations的情况下在Python中生成列表的增加排列:

我正在尝试创建一个函数,它将生成列表的所有排列,但仅限于len(n)组,并且只从左到右增加。例如,如果我有列表l = [2,4,5,7,9]和n = 4,结果应包括[2,4,5,7],[2,4,7,9],[ 2,5,7,9]但不是[9,7,4,2],[9,4,7,2]。这是我到目前为止所做的:

def permutation(lst):

    if len(lst) == 0:
        return []

    if len(lst) == 1:
        return [lst]

    l = []

    for i in range(0, len(lst)):
       m = lst[i]

       new = lst[:i] + lst[i+1:]

       for p in permutation(new):
           l.append([m] + p)
    return l

测试:

data = list([1,2,3,4,5,6])
for p in permutation(data):
    print p
python algorithm combinations permutation
1个回答
0
投票

你所描述的正是itertools.combinations所做的:

from itertools import combinations
l = [2,4,5,7,9]
n = 4
for c in combinations(l, n):
    print(list(c))

这输出:

[2, 4, 5, 7]
[2, 4, 5, 9]
[2, 4, 7, 9]
[2, 5, 7, 9]
[4, 5, 7, 9]

但是如果你不想真正使用itertools.combinations,你可以参考如何在documentation中用Python实现它:

def combinations(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(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)
© www.soinside.com 2019 - 2024. All rights reserved.