简体   繁体   English

组合没有Python中所有元素的重复

[英]Combinations without duplicates of all elements in Python

To clarify the picture, if i have a string: 为了澄清图片,如果我有一个字符串:

'pac'

I would want to get the list of every permutation of it, in this example: 在这个例子中,我想获得它的每个排列的列表:

['p', 'a', 'c', 'pa', 'pc', 'pac']

Just like i would type any of it in some search engine like the one on Ebay and it would pop up "pac" as a suggestion. 就像我会在某些搜索引擎中输入任何一个类似Ebay上的那个,它会弹出“pac”作为建议。

Code bellow is what i achieved thus far, but it's obviously not working as it should. 代码吼叫是我迄今为止所取得的成就,但它显然不能正常工作。 'Names' is just a list with multiple names, for instance: ['pac', 'greg', 'witch'] 'Names'只是一个包含多个名称的列表,例如:['pac','greg','witch']

    letters = {}
    for name in names:
        temp = []
        letter = []
        temp2 = []

        for let in name:
            let = let.lower()
            temp.append(let)
            letter.append(let)

        for i in range(0, len(name)):
            for j in range(1, len(name) - i):
                print(i, j, end='  ')

                to_add = letter[i] + temp[j]
                print(to_add, temp2)

                temp2.append(to_add)
                letter.append(to_add)
            temp = temp2
            temp2 = []

        letters[name] = letter
    return letters

If there is built-in function feel free to share it with me, but that's not the core of the problem. 如果有内置函数随时与我分享,但这不是问题的核心。

User standard library itertools : 用户标准库itertools

In [48]: T = 'pac'

In [49]: list(itertools.chain(*[itertools.combinations(T, i+1) for i in range(len(T))]))
Out[49]: [('p',), ('a',), ('c',), ('p', 'a'), ('p', 'c'), ('a', 'c'), ('p', 'a', 'c')]

It break down into: 它分解为:

1, itertools.combinations(['p', 'a', 'c'], i) to generate all the subsample of 'pac' with sample size i 1, itertools.combinations(['p', 'a', 'c'], i)生成样本大小为i的'pac'的所有子样本

2, repeat i for i=1, 2, 3 , and put the resultant three itertools.combination objects in a list 2,对i=1, 2, 3重复i ,并将得到的三个itertools.combination对象放在一个列表中

3, unpack the list from #2, and use the those as the parameter to generate an itertools.chain object (as the name implies, it will chain its args together). 3,从#2解压缩列表,并使用它们作为参数生成一个itertools.chain对象(顾名思义,它将链接其args)。 See more on arguments unpack 查看有关参数unpack的更多信息

In a lot of real world use cases, especially when the total number of the elements are large, you don't actual want to make a list out of the itertools.chain object. 在很多现实世界的用例中,特别是当元素的总数很大时,你实际上并不想从itertools.chain对象中创建一个列表。 The point of using itertools are often to achieve memory efficiency by avoiding having to putting all its members in memory. 使用itertools目的通常是通过避免将所有成员放在内存中来实现内存效率。

(if you don't want tuple s just add a ''.join to get them back to strings) (如果你不想要tuple只需添加一个''.join来让它们回到字符串)

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

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