我有一个像这样的列表对象
value = [<employee 'Mark Twain' as 'Captain'>,<employee 'Huckle' as 'Cowboy'>]
现在我希望雇员和一个单独的变量,如emplo [0]和[0]喜欢
emplo[0] = 'Mark Twain'
as[0] = 'Captain'
emplo[1] = 'Huckle'
as[1] = 'Cowboy'
从值循环遍历列表并返回值
是否有任何可能的代码将列表值拆分为单独的变量?
答案 0 :(得分:0)
最好是访问对象&#39;基于这些对象实现或读取其属性的方法的数据。但是,如果没有其他信息,您可以将这些信息分开,假设没有任何名称或作业包含'
。
打印时
value = [<employee 'Mark Twain' as 'Captain'>,<employee 'Huckle' as 'Cowboy'>]
这是每个对象的repr
结果,因此您可以在两个列表推导中调用split
:
employees = [repr(obj).split("'")[1] for obj in value]
positions = [repr(obj).split("'")[3][:-1] for obj in value]
repr(value[0])
将生成<employee 'Mark Twain' as 'Captain'>
,因此当您致电split("'")
时,您会得到如下列表:
['<employee ', 'Mark Twain', ' as ', 'Captain>']
因此,在该结果上调用[1]
获取员工姓名,并且调用[3]
将获得他们的工作,尽管您还需要将该字符串中的最后一个字符切片为{ {1}},这就是我添加>
。
答案 1 :(得分:0)
假设您的employees
是类对象,如下所示
class Employee(object):
name = ''
nickname = ''
emplo = [employee.name for employee in employees]
nickname = [employee.nickname for employee in employees]
或1循环
emplo, nicks = [], []
for employee in employees:
emplo.append(employee.name)
nicks.append(employee.nickname)