如何使random.shuffle真正随机?

时间:2015-10-10 09:25:13

标签: python random shuffle

所以我有这个清单:

words = ["Games","Development","Keyboard","Speed","Typer","Anything","Alpha","Zealous","Accurate","Basics","Shortcut","Purpose","Window","Counter","Fortress","Modification","Computer","Science","History","Football","Basketball","Solid","Phantom","Battlefield","Advanced","Warfare","Download","Upload","Antidisestablishmentarianism","Supercalifragilisticexpialidocious","Discombobulation","Liberated","Assassin","Brotherhood","Revelation","Unity","Syndicate","Victory"]

我有这个将它洗牌并将其显示在标签上:

entry.delete(0, tkinter.END)
random.shuffle(words)
label.config(text=str(words[1]))
timeLabel.config(text="Time: " + str(time_score)+ "s")

我想知道如何使这种随机播放真正随机,因为尽管列表中有很多内容,但感觉我一遍又一遍地听到同一个字。 也许有一种方法可以从列表中删除一个值,这样它就不能再显示了?

2 个答案:

答案 0 :(得分:4)

变种@grael的解决方案是随机播放,然后使用list.pop删除项目。没有必要多次洗牌。

In [54]: words = ['foo','bar','baz','quux','bizby','squiggle']

In [55]: random.shuffle(words)

In [56]: while words: print(words.pop())
bizby
bar
foo
baz
squiggle
quux

答案 1 :(得分:3)

您可以尝试:

import random
random_word = random.choice(words)

从数组中选择随机单词。然后你可以这样做:

words.remove(random_word)

从数组中删除这个随机选择的单词,以避免再次获取它,如果你想获得下一个随机单词。

修改 - 回复评论

当我在下面运行此代码时,我每次都会得到不同的词。这是你正在寻找的逻辑吗?

words = ["Games","Development","Keyboard","Speed","Typer","Anything","Alpha","Zealous","Accurate","Basics","Shortcut","Purpose","Window","Counter","Fortress","Modification","Computer","Science","History","Football","Basketball","Solid","Phantom","Battlefield","Advanced","Warfare","Download","Upload","Antidisestablishmentarianism","Supercalifragilisticexpialidocious","Discombobulation","Liberated","Assassin","Brotherhood","Revelation","Unity","Syndicate","Victory"]

import random
while words:
    random_word = random.choice(words)
    print(random_word)
    words.remove(random_word)