简体   繁体   中英

Random question for random answer in python

can anybody help me to make something like this on Python? Example:

list = "Back", "Left", "Up"

now i want Python to take a random items from the lists above.

If Python take "Back" from the list then the answer is "Front" If "Up" the answer is "Down" If "Left" the answer is "Right"

That's all and sorry if it's complicated or not understandable.

You could use random.choice like this:

import random

questions_answers = [('Back', 'Front'), ('Up', 'Down'), ('Left', 'Right')]
question, answer = random.choice(questions_answers)
print(f"Q: {question}, A: {answer}")

You can create a mapping dictionary with your values.

For example:

from random import choice

tpl = "Back", "Left", "Up"
mapping = {'Back': 'Front', 'Up': 'Down', 'Left': 'Right'}

v = choice(tpl)
print('Python chose: {}, mapping is {}'.format(v, mapping[v]))

Prints:

Python chose: Up, mapping is Down

Look at the python built-in module "random". For this example:

import random
myList = ["Back", "Left", "Up"]
random_item_from_list = random.choice(list)

I would do this with a dictionary. Here's a snippet:

import random

mydict = {"back": "front", "left": "right", "up": "down"}

progchoice = random.choice(["back", "left", "up"])
answer = mydict[progchoice]

print(answer)

import necessary package:

import random

create input parameters:

list_obj = "Back", "Left", "Up"
results_obj = "Front", "Right", "Down"

create mapping between lists:

mapping = dict(zip(list_obj, results_obj))

return the result by randomly chosen key from mapping:

mapping[random.choice(list_obj)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM