如何在python中随机随机播放单词的字母?
例如,“cat”一词可能会改为“act”,“tac”或“tca”。
我想使用内置函数
执行而不使用答案 0 :(得分:7)
import random
word = "cat"
shuffled = list(word)
random.shuffle(shuffled)
shuffled = ''.join(shuffled)
print shuffled
...或以不同的方式完成,受到Dominic's answer ...
的启发import random
shuffled = ''.join(random.sample(word, len(word)))
答案 1 :(得分:7)
看看Fisher-Yates shuffle。它非常节省空间和时间,并且易于实施。
答案 2 :(得分:3)
This cookbook recipe在Python中有一个简单的Fisher-Yates改组实现。当然,由于你有一个字符串参数并且必须返回一个字符串,你需要一个第一个语句(比如参数名称是s
),如ary = list(s)
,并在return
语句中您将使用''.join
将字符数组ary
放回一个字符串中。
答案 3 :(得分:2)
return "".join(random.sample(word, len(word)))
用过:
word = "Pocketknife"
print "".join(random.sample(word, len(word)))
>>> teenockpkfi
答案 4 :(得分:0)
为了略微更低级别,这只是将当前字母与随后的字母交换。
from random import randint
word = "helloworld"
def shuffle(word):
wordlen = len(word)
word = list(word)
for i in range(0,wordlen-1):
pos = randint(i+1,wordlen-1)
word[i], word[pos] = word[pos], word[i]
word = "".join(word)
return word
print shuffle(word)
这不会以相同的概率创建所有可能的排列,但仍然可能没有你想要的
答案 5 :(得分:0)
这是一种不使用random.shuffle
的方法。希望random.choice
没问题。您应该对问题添加任何限制
>>> from random import choice
>>> from itertools import permutations
>>> "".join(choice(list(permutations("cat"))))
'atc'
此方法不如random.shuffle有效,因此对于长词来说会很慢
答案 6 :(得分:0)
from random import random
def shuffle(x):
for i in reversed(xrange(1, len(x))):
j = int(random() * (i+1))
x[i], x[j] = x[j], x[i]