【问题标题】:matlab like struct in pythonmatlab 类似于 python 中的结构
【发布时间】:2018-03-28 11:40:07
【问题描述】:

你能建议用python表示这个结构的简洁方法吗?

students = struct;
students(1).fname = 'john';
students(1).lname ='smith';
students(1).height = 180;

students(2).fname = 'dave';
students(2).lname = 'clinton';
students(2).height = 184;

谢谢!

【问题讨论】:

  • 词典列表或学生班级列表
  • 你能举个例子吗?
  • 我刚刚编写了一个类(名为“tree”),可以在 python3 中使用类似 matlab 的语法。对于最初的例子,我们可以这样写:students = tree() students.john.lname ='smith'students.john.height = 180 students.dave.lname = 'clinton'students.dave.height = 184 个学生。 other.lname = 'roger' students.other.height = 185 如果有人对“tree”类的源代码感兴趣,请告诉我。

标签: python matlab list struct


【解决方案1】:

在 Python 中,您可以创建一个类(有点像结构,但功能更多),如下所示:

class Student()
    def __init__(self, fname, lname, height):
        self.fname = fname
        self.lname = lname
        self.height = height

__init__ 函数描述了创建新学生记录所需的信息。 'self' 参数只是告诉 Python 你想将这些变量设置在一个实例(一个实际的学生记录)而不是类(这是学生记录的蓝图)上。然后,您可以按如下方式创建 Student 的实例:

my_student = Student('Space', 'Man', 180)

您可以创建许多这样的实例并将每个实例附加到一个列表中:

all_students = [] # An empty list
all_students.append(my_student) # using the instance we've already created
all_students.append(Student('Jingle', 'Sting', 180)) # a new instance

然后您可以按如下方式访问列表中的项目:

all_students[1]

通过创建类,您还可以创建适用于所有学生实例的方法。

class Student()
    def __init__(self, fname, lname, height):
        self.fname = fname
        self.lname = lname
        self.height = height

    def get_height_in_meters(self):
        return self.height / 100

并像这样使用它们:

my_student.get_height_in_meters()

您甚至可以使用适用于学生记录的方法直接从列表中对学生记录进行字符串访问,如下所示:

all_students[1].get_height_in_meters()

【讨论】:

    【解决方案2】:

    这可以通过创建一个字典列表来完成,如下所示:

    students = [
        {'fname': 'john', 'lname': 'smith', 'height': 180},
        {'fname': 'dave', 'lname': 'clinton', 'height': 184}
    ]
    

    然后,您可以通过 students[n] 获取第 n 个学生,或者通过 students[n]['fname'] 从第 n 个学生获取特定字段

    【讨论】:

      【解决方案3】:

      使用命名元组列表:

      import collections
      harry = student(fname="harry", lname="Potter", height=160)
      hermione = student(fname="hermione", lname="Granger", height=140)
      
      students = [
          harry,
          hermione
      ]
      print(students[0].fname)
      print(students[1].fname)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-26
        • 1970-01-01
        • 2021-12-02
        • 1970-01-01
        • 2016-01-25
        • 1970-01-01
        • 2022-07-06
        相关资源
        最近更新 更多