简体   繁体   English

在字典python中创建格式化的值

[英]Create formatted values in Dictionary python

Hi I recently started programming and ran into a little problem with one of the exercises on exercism. 嗨,我最近开始编程,在练习运动的一个练习中遇到了一个小问题。 The exercise: ( https://github.com/exercism/xpython/tree/master/grade-school ?) 练习:( https://github.com/exercism/xpython/tree/master/grade-school ?)

I cannot get it to pass the last test. 我无法通过最后的测试。 It demands that the output is in the following way: 它要求输出采用以下方式:

sorted_students = { 3: ("Kyle",), 4: ("Christopher", "Jennifer",), 6: ("Kareem",) } sorted_students = {3:(“” Kyle“,),4:(” Christopher“,” Jennifer“,),6:(” Kareem“,)}

I store the information in a dictionary with the grades being the keys and the students contained in a set as values. 我将信息存储在字典中,其中等级是键,而集合中包含的学生则是值。 The last test however wants the values in the dictionary to be some sort of list and I do not know how to create this. 但是,最后一个测试希望字典中的值是某种列表,并且我不知道如何创建它。 My solution so far outputs the correct values with additional []brackets around the values. 到目前为止,我的解决方案输出正确的值,并在值周围带有附加的[]括号。 The error I get is as follows: 我得到的错误如下:

{3: ('Kyle',), 4: ('Christopher', 'Jennifer'), 6: ('Kareem',)} != {3: [('Kyle',)], 4: [('Christopher',), ('Jennifer',)], 6: [('Kareem',)]} {3:('Kyle',),4:('Christopher','Jennifer'),6:('Kareem',)}!= {3:[('Kyle',)],4:[(' Christopher',),(''Jennifer',)],6:[('Kareem',)]}

My code so: 我的代码是这样的:

class School:
def __init__(self,name):
    self.name = name
    self.db={}

def add(self,student, grad):
    if grad not in self.db:
        self.db[grad]={student}
    else:
        self.db[grad].add(student)

def grade(self,grad):
    if grad not in self.db:
        return set()
    else:
        return self.db[grad]

def sort(self): #where I fail
    newdict={} #new dictionary 
    for i in self.db: 
        newdict[i]=[(k,) for k in self.db[i]] #converst from set to list
    return newdict

The test demands a dictionary that maps integer to tuples. 该测试需要一个将整数映射到元组的字典。 Note the round parenthesis (this denotes a tuple). 注意圆括号(这表示一个元组)。

in your sort method you want: 在您想要的排序方法中:

return {g:tuple(s for s in self.db[g]) for g in self.db}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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