silver_river
silver_river

Reputation: 169

Return multiple lines into list

I have Result:

Alice
Washington Street
Doctor
Wong Li
Lincoln Street
Teacher
Suresh
Hamilton Street
Engineer

I can turn it into list by:

>>>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']

But what I need is

[['Alice', 'Washington Street', 'Doctor'], ['Wong Li', 'Lincoln Street', 'Teacher'], ['Suresh', 'Hamilton Street', 'Engineer']]

...basically group it by every 3 lines

After that I will use pandas to tabulate it into three column of name, address and occupation.

Upvotes: 0

Views: 117

Answers (2)

user2390182
user2390182

Reputation: 73480

Build a list of the desired slices using appropriate values by a range with proper start, stop, step values:

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']]

Upvotes: 2

Sreeram TP
Sreeram TP

Reputation: 11927

You can make the list result_list like you did and then use list comprehension with appropriate slicing..

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']]

Upvotes: 2

Related Questions