简体   繁体   English

排列列表中的重复项

[英]Duplicates in list of permutations

I am using the permutations function from the itertools library to print a list of permutations for a string.我正在使用itertools库中的permutations function 来打印字符串的排列列表。 In this case, it is baca .在这种情况下,它是baca However, the output list has duplicates of each element element.但是,output 列表具有每个元素元素的重复项。 Here it is:这里是:

['aabc', 'aabc', 'aacb', 'aacb', 'abac', 'abac', 'abca', 'abca', 'acab', 'acab', 'acba', 'acba', 'baac', 'baac', 'baca', 'baca', 'bcaa', 'bcaa', 'caab', 'caab', 'caba', 'caba', 'cbaa', 'cbaa']

Here is my code.这是我的代码。 It's pretty straight forward.这很简单。 I don't see anything in my code that would produce this behavior.我在我的代码中看不到任何会产生这种行为的东西。

from itertools import permutations

def rearrangeWord(word):
    p = [''.join(i) for i in permutations(word) ]
    print(sorted(p))

rearrangeWord('baca')

multiset_permutations can find the permutations with multiple items. multiset_permutations可以找到具有多个项目的排列。

>>> from sympy.utilities.iterables import multiset_permutations
>>> s = 'baca'


>>> for item in multiset_permutations(s):
    print(item)


['a', 'a', 'b', 'c']
['a', 'a', 'c', 'b']
['a', 'b', 'a', 'c']
['a', 'b', 'c', 'a']
['a', 'c', 'a', 'b']
['a', 'c', 'b', 'a']
['b', 'a', 'a', 'c']
['b', 'a', 'c', 'a']
['b', 'c', 'a', 'a']
['c', 'a', 'a', 'b']
['c', 'a', 'b', 'a']
['c', 'b', 'a', 'a']

You are duplicating all 'aa' permutations.您正在复制所有“aa”排列。

print(sorted(set(p)))

If you sort the word first (which is much cheaper), you don't need to sort afterwards:如果先对单词进行排序(便宜得多),则不需要事后排序:

>>> [*dict.fromkeys(map(''.join, permutations(sorted('baca'))))]
['aabc', 'aacb', 'abac', 'abca', 'acab', 'acba', 'baac', 'baca', 'bcaa', 'caab', 'caba', 'cbaa']

This solved my problem:这解决了我的问题:

print(sorted(dict.fromkeys(p)))

Now this is the output:现在这是 output:

['aabc', 'aacb', 'abac', 'abca', 'acab', 'acba', 'baac', 'baca', 'bcaa', 'caab', 'caba', 'cbaa']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM