获取python中没有重复项的列表的所有排列?

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

我正在尝试编写获取一组字符串的脚本-

["ab", "ls", "u"]

然后创建它们的所有可能组合,但不一定要全部使用它们。我希望上述示例的可能输出为:


ab
ab ls
ab ls u
ab u ls
ab u

ls
ls ab
ls ab u
ls u ab
ls u

u
u ls
u ls ab
u ab ls
u ab

我的脚本,删除了它所做的其他事情:

stuff = ["ab", "ls", "u"]

for subset in itertools.permutations(stuff):
    concat = ""
    for part in subset:
        concat = concat + part

    #the rest of my script now uses this data

返回:

ablsu
abuls
lsabu
lsuab
uabls
ulsab

我将如何使其返回我想要的东西?

python python-3.x itertools
4个回答
2
投票

您可以同时使用组合和排列。这应该能够使您前进

a = ["ab", "ls", "u"]
for i in range(1, len(a)+1):
    for comb in combinations(a, i):
        for perm in permutations(comb):
            print(perm)

输出:

('ab',)
('ls',)
('u',)
('ab', 'ls')
('ls', 'ab')
('ab', 'u')
('u', 'ab')
('ls', 'u')
('u', 'ls')
('ab', 'ls', 'u')
('ab', 'u', 'ls')
('ls', 'ab', 'u')
('ls', 'u', 'ab')
('u', 'ab', 'ls')
('u', 'ls', 'ab')

您可以按照自己的意愿处理comb


2
投票

当您提供包含3个元素排列的列表时,将返回所有3个元素的结果。您需要提供1个元素才能在输出中获得ab /ls/ u。您需要提供2个元素才能在输出中获得ab ls / ab u

因此您可以通过使用列表中的1/2元素调用它来使用同一程序。

stuff = ["ab", "ls", "u"]

for subset in itertools.permutations(stuff):
    concat = ""
    for part in subset:
        concat = concat + part

    #the rest of my script now uses this data

stuff = ["ab", "ls"]

for subset in itertools.permutations(stuff):
    concat = ""
    for part in subset:
        concat = concat + part


stuff = ["ls", "u"]

for subset in itertools.permutations(stuff):
    concat = ""
    for part in subset:
        concat = concat + part


1
投票
stuff = ["ab", "ls", "u"]
final_list = []
for subset in itertools.permutations(stuff):
    concat = ""
    for part in subset:
        concat = concat + part
        final_list.append(concat)

print(final_list)

['ab',
 'abls',
 'ablsu',
 'ab',
 'abu',
 'abuls',
 'ls',
 'lsab',
 'lsabu',
 'ls',
 'lsu',
 'lsuab',
 'u',
 'uab',
 'uabls',
 'u',
 'uls',
 'ulsab']

0
投票
import itertools

stuff = ["ab", "ls", "u"]

for i in range(len(stuff) + 1):
    for x in itertools.permutations(stuff[:i]):
        print(x)

但是此解决方案显示了所有排列::

()
('ab',)
('ab', 'ls')
('ls', 'ab')
('ab', 'ls', 'u')
('ab', 'u', 'ls')
('ls', 'ab', 'u')
('ls', 'u', 'ab')
('u', 'ab', 'ls')
('u', 'ls', 'ab')
© www.soinside.com 2019 - 2024. All rights reserved.