如何在python中将列表拆分为不同的字符串

时间:2015-09-18 10:22:13

标签: python list split

我有一个像这样的列表对象

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'

从值循环遍历列表并返回值

是否有任何可能的代码将列表值拆分为单独的变量?

2 个答案:

答案 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)