如何在python 3.X中更改字符串中的字符顺序? [重复]

时间:2022-05-30 18:22:43

This question already has an answer here:

这个问题在这里已有答案:

let's say for example that I got 100 random words (not even real words just words)... like "ABCD" and I want to make a program that takes a word like the one I mentioned and prints you all the options of this word in random order. for example the word "ABC" will print: "ABC", "BAC", CAB", "BCA", "CBA". I could do it manually but if I have 100 words I can't... so how do I write a code that does it in python?

比方说,我有100个随机单词(甚至不是真正的单词只是单词)...就像“ABCD”一样,我想制作一个像我提到的那个单词的程序并打印出这个单词的所有选项以随机顺序。例如单词“ABC”将打印:“ABC”,“BAC”,CAB“,”BCA“,”CBA“。我可以手动完成但是如果我有100个单词我就不能......那么怎么做我写了一个在python中执行它的代码?

1 个解决方案

#1


1  

You can do this by using itertools:

你可以使用itertools来做到这一点:

import itertools
import random

words = ['word1', 'word2', 'word3']

for word in words:
    permutations_list = [''.join(x) for x in itertools.permutations(word)]
    random.shuffle(permutations_list)
    print(permutations_list)

#1


1  

You can do this by using itertools:

你可以使用itertools来做到这一点:

import itertools
import random

words = ['word1', 'word2', 'word3']

for word in words:
    permutations_list = [''.join(x) for x in itertools.permutations(word)]
    random.shuffle(permutations_list)
    print(permutations_list)