我正在尝试编写一个代码来打乱句子中的单词并返回一个不同顺序的字符串
from random import shuffle
def scramble():
a=len("this is a sentence")
for i in range(a):
random.shuffle("this is a sentence")
print(random.shuffle)
不确定我是否走在正确的轨道上,但是我相信循环可能是问题所在
我正在尝试编写一个代码来打乱句子中的单词并返回一个不同顺序的字符串
from random import shuffle
def scramble():
a=len("this is a sentence")
for i in range(a):
random.shuffle("this is a sentence")
print(random.shuffle)
不确定我是否走在正确的轨道上,但是我相信循环可能是问题所在
random.shuffle
适用于 aa 序列,而不是字符串。因此,首先,使用str.split
将句子拆分为单词列表,调用shuffle
它,然后再次使用将其转换为字符串str.join
:
from random import shuffle
def scramble(sentence):
split = sentence.split() # Split the string into a list of words
shuffle(split) # This shuffles the list in-place.
return ' '.join(split) # Turn the list back into a string
print scramble("this is a sentence")
输出:
sentence a this is