从令牌列表生成所有可能的字符串

2024-06-26 00:27:54 发布

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

我有一个令牌列表,比如:

hel
lo
bye

我想生成这些字符串的所有可能组合,比如:

hello
lohel
helbye
byehel
lobye
byelo

语言不重要,有什么建议吗?

我找到了Generating permutations using bash,但这使排列在一行上。


Tags: 字符串语言hellolo列表建议byegenerating
3条回答

考虑到其他语言是可以接受的:

#!/usr/bin/perl

use strict; use warnings;
use Algorithm::Combinatorics qw(permutations);

my $data = [ qw( hel lo bye ) ];
my $it = permutations($data);

while ( my $p = $it->next ) {
    print @$p, "\n";
}
hellobye
helbyelo
lohelbye
lobyehel
byehello
byelohel

您的示例可以用Python编写为

from itertools import combinations
print list(combinations(["hel", "lo", "bye"], 2))

要再次将输出合并到字符串:

print ["".join(a) for a in combinations(["hel", "lo", "bye"], 2)]

如果您对这个函数的实际实现感兴趣,请查看documentation

^{}可以帮你。

>>> l = ['hel', 'lo', 'bye']
>>> list(itertools.permutations(l, 2))
[('hel', 'lo'), ('hel', 'bye'), ('lo', 'hel'), ('lo', 'bye'), ('bye', 'hel'), ('bye', 'lo')]

或者如果需要组合,可以使用^{}

>>> l = ['hel', 'lo', 'bye']
>>> list(itertools.combinations(l, 2))
[('hel', 'lo'), ('hel', 'bye'), ('lo', 'bye')]

相关问题 更多 >