Python - Randomly select words to display in a qui

2019-09-22 04:26发布

问题:

This question already has an answer here:

  • How to randomly select an item from a list? 13 answers

I'm in need of some help. Here we have my two lists:

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"]

Okay, so many people are misunderstanding me, so I have these two lists, I use the random.choice to pick a word from each lists, once we have those words, I needed them to be printed out as a question such as, if hot and weak are selected, then it would be displayed as, "Hot is to cold as weak is to___?" I really need help on this, and detailed steps would be appreciated.

回答1:

Use the random library to make a random choice and use zip to make sure each element is associated with it's opposite:

import random

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

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


回答2:

You can use the random package and use the random.choice function:

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?")


回答3:

Try...

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