python - python脚本 - 调用函数的问题
问题描述
目前我正在开发一个项目,该项目是一个脚本,它从定义的列表中生成一个随机问题,并要求用户对这些问题进行加权,最后返回一个字典,显示每个问题的权重
问题是我不确定在哪里调用主函数,而且脚本返回一个空字典!
谁能帮我解决这个问题
import random
dict = {
"easy":["q1", "q2", "q3"],
"mid":['q4', 'q5', 'q6', 'q7'],
"hard":['q8', 'q9', 'q10', 'q11', 'q12']
}
tamplate = []
def make_random_tamp():
# print(random.choices(quistions))
i = 0
e = 0
m = 0
h = 0
random_easy_q = ''
random_mid_q = ''
random_hard_q = ''
while (i < 6):
while(e < 2):
random_easy_q = random.choices(dict["easy"])
if random_easy_q not in tamplate:
tamplate.append(random_easy_q)
e+=1
i+=1
continue
while(m < 2):
random_mid_q = random.choices(dict["mid"])
if random_mid_q not in tamplate:
tamplate.append(random_mid_q)
m+=1
i+=1
continue
while(h < 2):
random_hard_q = random.choices(dict["hard"])
if random_hard_q not in tamplate:
tamplate.append(random_hard_q)
h+=1
i+=1
continue
return tamplate
make_random_tamp()
w_quistion = {}
def wheights(tamplate, dict):
for i in tamplate:
j=0
if tamplate[j] in dict["easy"]:
w_quistion[input("please enter wheight from 1-5 to this quistion :")] = tamplate[j]
j+=1
elif tamplate[j] in dict["mid"]:
w_quistion[input("please enter a wheight from 6-15 to this quistion :")] = tamplate[j]
j+=1
elif tamplate[j] in dict["hard"]:
w_quistion[input("please enter a weight from 15-25 to this quistion :")] = tamplate[j]
j+=1
return w_quistion
print(wheights(tamplate, dict)) ```
解决方案
您的实施中有两个主要问题:
- 您定义
tamplate
为一个空列表,但函数的返回值make_random_tamp
未分配给tamplate
. - 您的字典值是列表对象,因此您需要用于
extend()
在主列表中添加元素,否则它将是列表列表。
import random
def make_random_tamp():
i = 0
e = 0
m = 0
h = 0
random_easy_q = ''
random_mid_q = ''
random_hard_q = ''
tamplate = []
while (i < 6):
while(e < 2):
random_easy_q = random.choices(dict_ob["easy"])
if random_easy_q not in tamplate:
tamplate.extend(random_easy_q) # use extend instead of append
e+=1
i+=1
continue
while(m < 2):
random_mid_q = random.choices(dict_ob["mid"])
if random_mid_q not in tamplate:
tamplate.extend(random_mid_q)
m+=1
i+=1
continue
while(h < 2):
random_hard_q = random.choices(dict_ob["hard"])
if random_hard_q not in tamplate:
tamplate.extend(random_hard_q)
h+=1
i+=1
continue
return tamplate
def wheights(tamplate, dict_ob):
w_quistion = {} # create local object here
# other code here
return w_quistion
tamplate = make_random_tamp()
print(wheights(tamplate, dict_ob))
除了上述问题,您应该避免使用dict
对象名称等关键字,并且字典w_quistion
可以在wheights()
函数中声明为本地对象。
注意:为简洁起见,我删除了部分代码。
推荐阅读
- flutter - Checkbox form validation
- c# - 如何处理 dot net core web api 中的 OPTION 标头
- javascript - Transpile typescript into plain Javascript
- spring-batch - Spring Batch:SingleItemPeekableItemReader 有时无法正常工作
- javascript - How to replace item by dropping another item on it using ng2-dnd library
- awk - sed delete lines matching pattern between 2 files
- java - 平铺地图上的 LibGDX AStar 寻路
- sql - Should there be a foreign key "to" an associative entity, or "from" the associative entity?
- shiny - highlighting text on shiny
- angular - 如何在 Angular 6 中迭代 ngcontainer 标签