我有结果:
Alice
Washington Street
Doctor
Wong Li
Lincoln Street
Teacher
Suresh
Hamilton Street
Engineer
我可以通过以下方式将其转换为列表:
>>>result_list = [y for y in (x.strip() for x in result.splitlines()) if y] #which i found it in SO
>>>result_list
['Alice', 'Washington Street', 'Doctor', 'Wong Li', 'Lincoln Street', 'Teacher', 'Suresh', 'Hamilton Street', 'Engineer']
但我需要的是
[['Alice', 'Washington Street', 'Doctor'], ['Wong Li', 'Lincoln Street', 'Teacher'], ['Suresh', 'Hamilton Street', 'Engineer']]
...基本上按每3行分组
之后我将使用熊猫将其列为三列名称,地址和职业。
答案 0 :(得分:2)
使用具有适当start, stop, step
值的范围的适当值构建所需切片的列表:
result_list = [result_list[i:i+3] for i in range(0, len(result_list), 3)]
# [['Alice', 'Washington Street', 'Doctor'], ['Wong Li', 'Lincoln Street', 'Teacher'], ['Suresh', 'Hamilton Street', 'Engineer']]
答案 1 :(得分:2)
你可以像你一样制作列表result_list
,然后使用列表理解和适当的切片..
result_list = [y for y in (x.strip() for x in result.splitlines()) if y]
result_list = [result_list[i:i+3] for i in range(0, len(result_list), 3)]
# output : [['Alice', 'Washington Street', 'Doctor'], ['Wong Li', 'Lincoln Street', 'Teacher'], ['Suresh', 'Hamilton Street', 'Engineer']]