Let's say I have a file like this (pretend it were a matri开发者_如何学Gox):
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:
f = open('file.txt')
lines = f.readlines()
matrix = [[a for a in b[:4]] for b in lines] # this gets all columns, up to 4
Slice each line up to the 3th column: matrix = [[a for a in b][:3] for b in lines]
"but with only columns up to 3"? What is this supposed to mean? Based on your example, do you mean "only the first four columns"? If that's the case, simple:
with f as open('file.txt'):
matrix = [list(line[:4]) for line in f]
Calling readlines
is unnecessary (worse, harmful as it consumes much memory for large files), you can iterate the lines just file.
精彩评论