如何交换1个字母并在python中给出所有可能的字母

如何只交换“一个”字母并在python3中给出所有可能的输出并追加到列表中

例如:单词“ study” 我们将拥有所有可能的输出,例如

swap the s:
tsudy,tusdy,tudsy,tudys,#swap the t:
tsudy,sutdy,sudty,sudyt
#also with u,d,y:
...
supercow2110 回答:如何交换1个字母并在python中给出所有可能的字母

您可以将单词转换为字符列表,

chars = list(word)

使用其位置从列表中删除选定的字符

chars.pop(index)

,然后将此字符添加到此列表的不同位置

new_chars = chars[:pos] + [char] + chars[pos:]

代码:

word = 'study'

for index,char in enumerate(word):
    print('char:',char)
    # create list without selected char
    chars = list(word)
    chars.pop(index)

    # put selected char in different places
    for pos in range(len(chars)+1):
        # create new list 
        new_chars = chars[:pos] + [char] + chars[pos:]
        new_word = ''.join(new_chars)

        # skip original word
        if new_word != word:
            print(pos,'>',new_word)

结果:

char: s
1 > tsudy
2 > tusdy
3 > tudsy
4 > tudys
char: t
0 > tsudy
2 > sutdy
3 > sudty
4 > sudyt
char: u
0 > ustdy
1 > sutdy
3 > stduy
4 > stdyu
char: d
0 > dstuy
1 > sdtuy
2 > stduy
4 > stuyd
char: y
0 > ystud
1 > sytud
2 > styud
3 > stuyd

顺便说一句::我不会将其称为"swapping",而是"moving"字符。在“交换”中​​,我宁愿替换两个字符-即。在a中将cabcd交换会得到cbad,而不是bcad(例如在“移动”中)

本文链接:https://www.f2er.com/3170109.html

大家都在问