根据结果​​形成字典

时间:2018-11-14 15:39:27

标签: python-3.x

将这些结果添加到字典中的最佳方法是什么?

class Student:
    def __init__(self, name, age):
        if type (name) == str and type(age)  == int or type(age)  == float:

            self.name = name
            self.age = age
        else :
            raise ValueError ("data type error")

 s1 = Student ('Chris Sanford',22)
 s2 = Student (' Tate', 24)
 s3 = Student ('Adèle Bernard', 17)
 s4 = Student ('Gabrielle Francis.', 83)

 result = {s1.name: s1.age, s2.name: s2.age, s3.name: s3.age,  s4.name:s4.age}
 print (result)

1 个答案:

答案 0 :(得分:0)

.\\

表达式structure_list = ['.', ['A', 'B', 'C', 'D', 'E', 'F']], ['A', ['G', 'H']], ['A\\G', []], ['A\\H', ['K', 'L']], ['A\\G\\K', []], ['A\\G\\L', []], ['B', ['I', 'J']], ['B\\I', []], ['B\\J', []], ['C', []], ['D', []], ['E', []], ['F', ['M']], ['F\\M', []] if __name__ == '__main__': import os import sys app = QtGui.QApplication(sys.argv) w = QtGui.QTreeView() model = TemplateTreeModel() w.setModel(model) model.appendRow(Node(".")) for root, dirs in structure_list: depth = root.split(os.sep) if not root.startswith("."): # append .\\, # by example if root is "A\\G" then the results is: # ".\\A\\G" root = "." + os.sep + root it = model.item_from_path(root, os.sep) model.appendRows([Node(_dir) for _dir in dirs], it) w.expandAll() w.resize(640, 480) w.show() sys.exit(app.exec_()) 被称为字典理解,可用于使用列表中的项创建字典以为每个键提供数据:对值。在这种情况下,class Student: def __init__(self, name, age): if type (name) == str and type(age) == int or type(age) == float: self.name = name self.age = age else : raise ValueError ("data type error") students = [Student('Chris Sanford',22), Student(' Tate', 24), Student('Adèle Bernard', 17), Student ('Gabrielle Francis.', 83)] result = {student.name: student.age for student in students} print (result) 的意思是“对于名为{student.name: student.age for student in students}的可迭代对象中的每个元素,请给我一个名为student in students的变量,然后可以在表达式的左侧使用单词{ {1}}