This question already has an answer here:
这个问题在这里已有答案:
- Finding all possible permutations of a given string in python 17 answers
- 在python 17答案中查找给定字符串的所有可能排列
- Best way to randomize a list of strings in Python 4 answers
- 在Python 4答案中随机化字符串列表的最佳方法
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)