Basically I have a text file:
-1 2 0
0 0 0
0 2 -1
-1 -2 0
0 -2 2
0 1 0
Which I want to be put into a list of lists so it looks like:
[[-1,2,0],[0,0,0],[0,2,-1],[-1,-2,0],[0,-2,2],[0,1,0]]
I have this code so far but it produces a list of strings within lists.
import os
f = open(os.path.expanduser("~/Desktop/example board.txt"))
for line in f:
for i in line:
line = line.strip()
line = line.replace(' ',',')
line = line.replace(',,',',')
print(i)
print(line)
b.append([line])
That produces [['-1,2,0'],['0,0,0'],['0,2,-1'],['-1,-2,0'],['0,-2,2'],['0,1,0']]
Which is almost what I want except with the quotation marks.
I would recommend just using numpy for this rather than reinvent the wheel...
>>> import numpy as np
>>> np.loadtxt('example board.txt', dtype=int).tolist()
[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]
Note: depending on your needs, you may well find a numpy array to be a more useful data structure than a list of lists.
Use the csv
module:
import csv
with open(r'example board.txt') as f:
reader = csv.reader(f, delimiter='\t')
lines = list(reader)
print lines
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With