具有唯一值的排列排列根据元素的位置而不是其值来生成元素被视为唯一的位置。所以基本上我想避免这样的重复:>>> list(itertools.permutations([1, 1, 1]))[(1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1)]事后过滤是不可能的,因为在我的情况下排列的数量太大。有谁知道一个合适的算法吗?非常感谢!编辑:我主要想要的是:x = itertools.product((0, 1, 'x'), repeat=X)x = sorted(x, key=functools.partial(count_elements, elem='x'))这是不可能的,因为sorted创建一个列表,则itertools.Products的输出太大。对不起,我应该描述一下实际的问题。
3 回答
陪伴而非守候
TA贡献1757条经验 获得超8个赞
class unique_element: def __init__(self,value,occurrences): self.value = value self.occurrences = occurrencesdef perm_unique(elements): eset=set(elements) listunique = [unique_element(i,elements.count(i)) for i in eset] u=len(elements) return perm_unique_helper(listunique,[0]*u,u-1)def perm_unique_helper(listunique,result_list,d): if d < 0: yield tuple(result_list) else: for i in listunique: if i.occurrences > 0: result_list[d]=i.value i.occurrences-=1 for g in perm_unique_helper(listunique,result_list,d-1): yield g i.occurrences+=1a = list(perm_unique([1,1,2]))print(a)
[(2, 1, 1), (1, 2, 1), (1, 1, 2)]
def permutations_with_replacement(elements,n): return permutations_helper(elements,[0]*n,n-1)#this is generatordef permutations_helper(elements,result_list,d): if d<0: yield tuple(result_list) else: for i in elements: result_list[d]=i all_permutations = permutations_helper(elements,result_list,d-1)#this is generator for g in all_permutations: yield g
yield
for g in perm_unique_helper(listunique,result_list,d-1): yield g
permutations_with_replacement
胡子哥哥
TA贡献1825条经验 获得超6个赞
from itertools import permutationsdef unique_permutations(iterable, r=None): previous = tuple() for p in permutations(sorted(iterable), r): if p > previous: previous = p yield pfor p in unique_permutations('cabcab', 2): print p
('a', 'a')('a', 'b')('a', 'c')('b', 'a')('b', 'b')('b', 'c')('c', 'a')('c', 'b')('c', 'c')
添加回答
举报
0/150
提交
取消