我试图弄清楚如何从元组列表中创建变量并将它们分配给一个类。
我的数据是这样组织的
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 循环以从 sublist[0] 创建变量,然后从中创建一个类(例如 sublist[0] = Employee(sublist[0], sublist[1], sublist[ 2]))?
最佳答案
你只需要
employees = [Employee(*v) for v in employee_list]
请注意,employees
和 Employee.elist
本质上是相同的
每个Employee
对象都已创建。
关于python - 如何从元组列表中创建变量并将其设置为类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39883083/