带有绑定值的python itertools排列

use*_*925 6 python performance python-itertools pandas

我想找到一个有绑定值的向量的有效排列.

例如,如果perm_vector = [0,0,1,2]我想获得输出的所有组合[0,0,1,2], [0,0,2,1], [0,1,2,0]等等,但我不想获得[0,0,1,2]两次,这是标准itertools.permutations(perm_vector)给出的.

我试过以下但是当它perm_vector grows在len 时它真的很慢:

vectors_list = []
for it in itertools.permutations(perm_vector):
    vectors_list.append(list(it))
df_vectors_list  = pd.DataFrame( vectors_list)
df_gb = df_vectors_list.groupby(list(df_vectors_list.columns)) 
vectors_list = pd.DataFrame(df_gb.groups.keys()).T
Run Code Online (Sandbox Code Playgroud)

实际上,问题是更加普遍的"加速"性质.主要时间用于创建长向量的排列 - 即使没有两面性,创建12个唯一值的向量的排列也需要"无穷大".是否有可能迭代地调用itertools而不访问整个排列数据但是处理它的串?

Rom*_*kar 0

这个怎么样:

from collections import Counter

def starter(l):
    cnt = Counter(l)
    res = [None] * len(l)
    return worker(cnt, res, len(l) - 1)

def worker(cnt, res, n):
    if n < 0:
        yield tuple(res)
    else:
        for k in cnt.keys():
            if cnt[k] != 0:
                cnt[k] = cnt[k] - 1
                res[n] = k
                for r in worker(cnt, res, n - 1):
                    yield r
                cnt[k] = cnt[k] + 1
Run Code Online (Sandbox Code Playgroud)