Read a file and generate a list of lists using list comprehensions

Question:

I’d like to read a file with the following input:

10
20
30

50
60
70

80
90
100

and generate the following output:

[['10', '20', '30'], ['50','60','70'] ... ]

using list comprehensions and not foor loops. Naturally the problem I’m facing is creating the nested list when a n character is detected. Of course ‘disclaimer’ the code would probably be more readable with for loops!

with open('file.txt', 'r') as f:
    result = [line.strip() for line in f.readlines() if line != 'n']

print(result)

// 
['10', '20', '30', '50', '60', '70']
// not correct
Asked By: George Katsanos

||

Answers:

Here is a solution using split (so, different from the solutions you are exploring with comprehensions).

with open('file.txt', 'r') as f:
    result = [s.split("n") for s in f.read().split("nn")]
print(result)

This other approach uses the functional-programming tools, comprehension and groupby, and so is more in the spirit of what you asked for.

from itertools import groupby

with open('file.txt', 'r') as f:
    result = [[s.strip() for s in group] for key, group in groupby(f, lambda x: x == "n") if not key]
print(result)
Answered By: Joshua Fox
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.