数组Python中的随机问题序列
我有5个数组,每个数组中有6个问题。数组Python中的随机问题序列,python,python-3.x,input,Python,Python 3.x,Input,我有5个数组,每个数组中有6个问题。 我需要脚本从每个数组中选择2个问题并创建一个输入函数。我想不出的部分是如何输出正确答案。我知道指定的输入是如何工作的,但随机输入又如何呢。我想您正在寻找这样的输入: randomNumber1=***some generated number (0 thru 6) randomNumber2=***some generated number (0 thru 6) array1=['what is the meaning of life', 'how far
我需要脚本从每个数组中选择2个问题并创建一个输入函数。我想不出的部分是如何输出正确答案。我知道指定的输入是如何工作的,但随机输入又如何呢。我想您正在寻找这样的输入:
randomNumber1=***some generated number (0 thru 6)
randomNumber2=***some generated number (0 thru 6)
array1=['what is the meaning of life', 'how far away is the sun',...]
array2=['what did is your favorite color', 'how many pennies are in 1 dollar'...]
q1=array1[randomNumber1]
q2=array2[randomNumber2]
input1=input(q1)
input2=input(q2)
#stores answers in a dictionary
answers={q1:input1, q2:input2}
我认为随机模块没有您想要的功能 但是如果你喜欢的话,建造一个是很容易的。Python很简单 这行吗
import random
from typing import Iterable
def get_sub_random_list(sub_length: int, iterable: Iterable) -> list:
iterable_copy = list(iterable)
result = []
for __ in range(sub_length):
length = len(iterable_copy)
if length == 0:
raise ValueError(f"the iterable should longer than {sub_length}")
index = random.choice(range(length))
result.append(iterable_copy[index])
del iterable_copy[index]
return result
例如:
>>> get_sub_random_list(1, [1, 2, 3, 4, 5, 6])
[5]
>>> get_sub_random_list(6, [1, 2, 3, 4, 5, 6])
[4, 1, 5, 2, 6, 3]
复杂度为+m:n是iterable的长度,m是循环的次数。提供代码尝试和解释会有帮助,谢谢!这很有帮助。