一个字符串的所有可能的排列

2024-10-03 09:18:06 发布

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

字符串为'january',

如何生成以下案例:

case1(替换1个字符)=>;取j并将其替换为所有ASCII字母(a-z)。然后对a,n,u,a,r,y做同样的处理

基本上我们会

(一年,一年,。。。。。,Zanuary)+(一月,jBanuary…..jZanuary)+…+(januarA,januarB,…,januarZ)

我已经用下面的代码完成了这一部分,但是,由于有很多排列,我不知道如何对多个字母执行此操作。在


monthName= 'january'
asci_letters = ['a' , 'b' , .... , 'z']

lst = list(monthName)
indxs = [i for i , _ in enumerate(monthName)]
oneLetter=[]

for i in indxs:
word = monthName
pos = list(word)
    for j in asci_letters:
        pos[i] = j
        changed = ("".join(pos))
        oneLetter.append(changed)

案例2:取2个字符并替换它们: (AAnuary,ABnuary,…,AZanuary)+(BAnuary,BBanuary。。。。,BZanuary)+(AaAuary,AaBuary,…,AaZuary)+。。。。。。+(januaAB。。。。,雅努阿兹)

案例3:对3个字符执行相同的操作

案例7:对7个字符(字符串长度)执行相同操作

总而言之,我想创建所有可能的替换情况,1个字母,2个字母,3个字母,直到字符串中的所有字母。在


Tags: 字符串inposfor字母案例listword
3条回答

很可能你不能把所有这些排列都记在记忆里,因为它很快就会变得非常拥挤。在

但是要获得案例的所有索引,可以使用itertools.combinations。对于1,它将给出单个指数:

from itertools import combinations

string_ = 'january'
length = len(string_)
print(list(combinations(range(length), 1)))
# [(0,), (1,), (2,), (3,), (4,), (5,), (6,)]

同样,您可以得到案例2-7的索引:

^{pr2}$

那么只需在给定的索引处插入itertools.productitertools.product

from itertools import product
import string

print(list(product(string.ascii_uppercase, repeat=1)))
# [('A',), ('B',), ('C',), ('D',), ('E',), ('F',), ('G',), ('H',), ('I',),
#  ('J',), ('K',), ('L',), ('M',), ('N',), ('O',), ('P',), ('Q',), ('R',), 
#  ('S',), ('T',), ('U',), ('V',), ('W',), ('X',), ('Y',), ('Z',)]

同样地,对于不同的重复,给出了“案例”。在

把这些放在一起:

def all_combinations(a_string, case):
    lst = list(a_string)
    length = len(lst)
    for combination in combinations(range(length), case):
        for inserter in product(string.ascii_uppercase, repeat=case):
            return_string = lst.copy()
            for idx, newchar in zip(combination, inserter):
                return_string[idx] = newchar
            yield ''.join(return_string)

然后,您可以通过以下方法获得每种情况下所需的所有排列:

list(all_combinations('january', 2))   # case2

list(all_combinations('january', 4))   # case4

list(all_combinations('january', 7))   # case7

或者如果你需要所有这些:

res = []
for case in [1, 2, 3, 4, 5, 6, 7]:
    res.extend(all_combinations('january', case))

但这需要大量的内存。在

您可以为此使用itertools.combinations_with_replacement,这将给您一个包含所有置换的iterator

from itertools import combinations_with_replacement

# First Param is an iterable of possible values, second the length of the 
# resulting permutations
combinations = combinations_with_replacement('ABCDEFGHIJKLMNOPQRSTUVWXYZ',7)

# Then you can iterate like this:
for combination in combinations:
    #Do Stuff here

不要试图将这个iterator转换为一个包含所有值的列表,因为您可能会得到一个MemoryException。在

对于您的距离,您可能需要使用python distance包。(您需要先通过pip安装它)。在

对于您的情况,您希望获得长度为7的字符a-z的所有组合(由于一月):

^{pr2}$

这将在productpermutations的帮助下完成您想要的一切:

from itertools import product, permutations

monthName= 'january'

letters = list('abcdefghijklmnopqrstuvwxyz')

n = len(monthName)
indxs = range(n)
mn = list(monthName)

cases = {k: [] for k in range(2, n+1)}
for num in range(2, n+1):
    letter_combos = list(product(*[letters for _ in range(num)]))
    positions = permutations(indxs, num)
    for p in positions:
        for l in letter_combos:
            l = iter(l)
            for i in p:
                mn[i] = next(l)
            mn = ''.join(mn)
            cases[num].append(mn)
            mn = list(monthName)

相关问题 更多 >