在python中获取列表的所有排列而不重复?

2024-04-26 10:10:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图写一个脚本,得到一组字符串-

["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

我怎样才能让它归还我想要的?你知道吗


Tags: 字符串in功能脚本示例forabls
3条回答

你可以同时使用组合和排列。这应该可以让你走了

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')

你可以处理任何你认为合适的事情

当你给出包含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

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']

相关问题 更多 >