Python - 随机选择要在测验中显示的单词 [重复]

Python - Randomly select words to display in a quiz [duplicate]

提问人:iHazo 提问时间:1/8/2015 最后编辑:iHazo 更新时间:1/8/2015 访问量:332

问:

我需要一些帮助。这里有我的两个清单:

wordlists1 = ["hot","summer", "hard", "dry", "heavy", "light", "weak", "male",
             "sad", "win",  "small","ignore", "buy", "succeed", "reject", "prevent", "exclude"]

wordlists2 = ["cold", "winter", "soft", "wet", "light", "darkness", "strong", "female", "happy", "lose", "big",
         "pay attention", "sell", "fail", "accept", "allow", "include"]

好吧,很多人误解了我,所以我有两个列表,我使用 random.choice 从每个列表中选择一个单词,一旦我们有了这些单词,我需要将它们打印成一个问题,例如,如果选择了 hot 和 weak,那么它会显示为,“热是冷,弱是to___?我真的需要这方面的帮助,详细的步骤将不胜感激。

python 列表 随机

评论


答:

1赞 smac89 1/8/2015 #1

使用随机库进行随机选择,并使用 zip 确保每个元素都与相反的元素相关联:

import random

words = zip(wordlist1, wordlist2)
print random.choice(words)

for word1, word2 in words:
    print word1, "is the opposite of", word2

评论

0赞 ianaya89 1/8/2015
您应该为这段代码添加一些解释。
0赞 willeM_ Van Onsem 1/8/2015 #2

您可以使用包并使用以下函数:randomrandom.choice

import random

wordlists1 = ["hot","summer", "hard", "dry", "heavy", "light", "weak", "male",
              "sad", "win",  "small","ignore", "buy", "succeed", "reject", "prevent", "exclude"]

wordlists2 = ["cold", "winter", "soft", "wet", "light", "darkness", "strong", "female", "happy", "lose", "big",
              "pay attention", "sell", "fail", "accept", "allow", "include"]

word1 = random.choice(wordlists1)
word2 = random.choice(wordlists2)
print("Are "+word1+" and "+word2+" opposites?")
0赞 eternauta 1/8/2015 #3

尝试。。。

import random      
print(" question " + random.choice(wordlists1) + " question " + random.choice(wordlists2))

评论

0赞 eternauta 1/8/2015
好吧,问题是你也必须保持单词成对。不是完全随机的。你想在同一个问题中冷热,对吧?否则,你会有这样的问题:“热是允许的,因为男性是___”,这对我来说没有意义。
0赞 eternauta 1/8/2015
尝试在二维中创建列表。