1

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
George Katsanos
  • 13,524
  • 16
  • 62
  • 98
  • Added a second duplicate link, in case the question is intended to be specifically about the mechanics of the list comprehension. The material is well covered. – Karl Knechtel Jan 26 '23 at 10:27

1 Answers1

1

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("\n\n")]
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)
Joshua Fox
  • 18,704
  • 23
  • 87
  • 147