gpt4 book ai didi

python - 我可以在python中设置random.randint()函数的条件吗

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:45 24 4
gpt4 key购买 nike

WORDS=("lorem","ipsum","python")
words = random.choice(WORDS)
correct = words
length = 0
while length <len(words):
i = random.randint(0,len(words))
print(words[i],end=" ")
length +=1

我正在尝试制作一个单词混淆游戏,其中单词中的字母应该混在一起。我想问是否可以设置一个条件,以便i不会一遍又一遍地重复相同的值

感谢任何帮助。

最佳答案

您可以使用random.shuffle它进行就地洗牌。例如:

>>> import random
>>> WORDS = ["lorem","ipsum","python"] # But you need `list` not `tuple`;
# tuples are immutable
>>> random.shuffle(WORDS)
>>> WORDS # List is shuffled
['ipsum', 'python', 'lorem']

要打乱元组中的每个单词,您需要执行以下操作:

shuffled_words= []

for word in WORDS:
word_list = list(word) # Typecast `str` to `list`
random.shuffle(word_list) # shuffle the list
shuffled_words.append(''.join(word_list)) # join the list to make `str`

shuffled_words 列表保存的值将是:

>>> shuffled_words
['omelr', 'spmiu', 'pynhot']

关于python - 我可以在python中设置random.randint()函数的条件吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41224937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com