How would I write the following code in list comprehension?
with open('some_file.txt', 'r') as f:
lines = f.readlines()
lines = [line.strip('\n') for line in lines]
list_of_lists = [[int(elm) for elm in line.split(' ')] for line in lines]
My file looks something like this:
3 8 6 9 4
4 3 0 8 6
2 8 3 6 9
3 7 9 0 3
Which means that:
grid = '3 8 6 9 4\n4 3 0 8 6\n2 8 3 6 9\n3 7 9 0 3'
Here a try , first split each lines and you will get a list of numbers as string, so map
function can be used to change it to int
:
with open('file.txt', 'r') as f:
k = [list(map(int,i.split())) for i in f.readlines()]
print(k)