如何检查使用随机模块打印的内容是否重复?

2024-04-25 13:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我目前的代码:

import random

words = ['a', 'b', 'c']
def abc():
    print(random.choice(words))
    input('Press Enter to Continue')
    abc()
abc()

我怎样才能使它每次从列表words打印一个单词时,都检查它以前是否重复过?我更希望答案是在python中没有模块,或者使用random模块。你知道吗


Tags: 模块to代码import列表inputdefrandom
1条回答
网友
1楼 · 发布于 2024-04-25 13:30:28

正如@John指出的,只要使用random.shuffle。你知道吗

random.shuffle(x[, random])

Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random().

random.shuffle(words)

print(words)

#loop
for word in words:
      print(word)

将提供:

IN : words = ['a', 'b', 'c']
OUT : ['c', 'a', 'b']                         #This is random

注1:使用shuffle的优点是没有两次获得相同元素的风险。你知道吗

注意2:但是要小心,因为使用shuffle也会影响存储数据的原始变量。如果您想保留原始序列,我建议您将数据复制到另一个变量中,并在shuffle中使用它。你知道吗

相关问题 更多 >