Let’s say I have a file like this (pretend it were a matrix):
abcde
fghik
lmnop
I want to put this in a 2d list but with only columns up to index 3:
# 0 1 2 3
[['a','b','c','d'],
['f','g','h','i'],
['l','m','n','o']]
How does one do this using a list comprehension? I know I could loop, but I’m looking for a cleaner way.
f = open('file.txt')
lines = f.readlines()
matrix = [[a for a in b] for b in lines] # this gets all columns, up to 4
I could also use enumerate/if in the inner list comprehension to check for column. Is that the cleanest?
If I understand the question correctly, this should work (but perhaps I’m over simplifying). Note the [:4] in the inner comprehension: