如何从元组列表中创建和设置变量作为类?

时间:2016-10-05 20:26:31

标签: python class loops tuples

我试图弄清楚如何从元组列表创建变量并将它们分配给一个类。

我有像这样组织的数据

 Name  Age  Status
 John  30   Employed

我已经创建了一个像这样的元组列表

 employeelist = [(John, 30, Employed), (Steve, 25, Part-Time)]

这样的课程设置如下

class Employee():
ecount = 0
elist = []

def __init__(self, name, age, emp_status):
    self.name = name
    self.age = age
    self.emp_status = emp_status
    self.lookup = {}
    Employee.ecount = Employee.ecount+1
    Employee.elist.append(self.name)

使用此代码,我可以将元组转换为类

的实例
 for i in range(0, len(employeelist),1):
    sublist = [str(n) for n in employeelist[i]]
    Employee(sublist[0], sublist[1], sublist[2])

但我无法访问它们。有没有办法考虑设置for循环以从子列表[0]创建变量,然后从中创建一个类(例如sublist [0] = Employee(sublist [0],sublist [1],sublist [ 2]))?

1 个答案:

答案 0 :(得分:4)

你只需要

employees = [Employee(*v) for v in employee_list]

请注意,employeesEmployee.elist基本相同 已创建每个Employee对象。