所以我需要为从第一个用户输入创建的列表中的每个项命名。 我的第一行代码如下:
num_assessment = int(input('How many assessments per student?'))
现在我需要用户为列表中的每个项目命名;例如:
How many assessments per student?:2
What type of assessment was assessment 1? Essay
How many marks is the Essay worth? 30
What type of assessment was assessment 2 ? Test
How many marks is the Test worth? 70
我可以使用什么功能来执行此操作?
答案 0 :(得分:1)
带有for
循环的字典是构建数据的一种方法。以下是一个例子。
num_assessment = int(input('How many assesments per student?\n'))
data = {}
for i in range(1, num_assessment+1):
data_type = input('What type of assessment was assessment {0}?\n'.format(i))
data_marks = int(input('How many marks is the {0} worth?\n'.format(data_type)))
data[i] = {'type': data_type, 'marks': data_marks}
示例强>
How many assesments per student?
2
What type of assessment was assessment 1?
essay
How many marks is the essay worth?
30
What type of assessment was assessment 2?
assignment
How many marks is the assignment worth?
50
<强>结果强>
print(data)
{1: {'marks': 30, 'type': 'essay'}, 2: {'marks': 50, 'type': 'assignment'}}
答案 1 :(得分:0)
你可以尝试这个:
n = int(input("How many assesments per student? "))
dct_values = {}
for i in range(1,n+1):
asesmnt = input("What type of assessment was assessment "+str(i)+"?
")
marks = int(input("How many marks is the "+asesmnt+" worth? "))
dct_values[i] = [{asesmnt:marks}]
print(dct_values)
它会将所有值存储在dict中,O / P将如下:
{1: [{'Essay': 30}], 2: [{'Test': 70}]}