我有两个列表:
list_a 包含我想要的题数和类型。一共有三种 1* 2* 3*
list_b 包含所有问题和类型,例如 'Q1:1*' 和 'Q1 is of type 1*' 被认为是一个问题..
到目前为止,我已经设法编写了一个循环遍历并随机选择问题数量和我想要的类型的代码。
import random
list_a = [[1, 1, 1]] # Read this as i want 1 question of type 1*,
1 question of type 2* and 1 question of type 3*
list_b = [['Q1:1*','Q1 is of type 1*', 'Q2:1*', 'Q2 is of type 1*', 'Q3:2*', 'Q3 is of type 2*',
'Q4:2*','Q4 is of type 2*', 'Q5:3*', 'Q5 is of type 3*', 'Q6:3*', 'Q6 is of type 3*']]
result = []
# Iterate over each type of question in list_a
for i in range(len(list_a[0])):
# Determine the number of questions required for this type
num_questions = list_a[0][i]
# Create a list of the indices of questions in list_b that match this type
question_indices = [idx for idx, q in enumerate(list_b[0]) if f":{i+1}*" in q]
# Randomly select the required number of questions and their corresponding elements
selected_indices = random.sample(question_indices, num_questions)
selected_questions = [list_b[0][idx] for idx in selected_indices]
selected_elements = [list_b[0][idx+1] for idx in selected_indices]
# Append the selected questions and elements to the result list
for q, e in zip(selected_questions, selected_elements):
result.append(q)
result.append(e)
# Print the final result
print(result)
我得到以下结果。
['Q2:1*', 'Q2 is of type 1*', 'Q3:2*', 'Q3 is of type 2*', 'Q6:3*', 'Q6 is of type 3*']
一切正常,除了我想让这段代码更动态。即
我想修改代码,使我的 list_a 和 list_b 成为列表的列表,例如
list_a = [[1,1,1],[1,2,1]]
list_b = [['Q1:1*','Q1 is of type 1*', 'Q2:1*', 'Q2 is of type 1*', 'Q3:2*', 'Q3 is of type 2*', 'Q4:2*','Q4 is of type 2*', 'Q5:3*', 'Q5 is of type 3*', 'Q6:3*', 'Q6 is of type 3*'],['Q7:1*','Q7 is of type 1*', 'Q8:1*', 'Q8 is of type 1*', 'Q9:2*', 'Q9 is of type 2*', 'Q10:2*','Q10 is of type 2*', 'Q11:3*', 'Q11 is of type 3*', 'Q12:3*', 'Q12 is of type 3*']]