Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import a string file into a list of lists?

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.

like image 860
Tom Avatar asked Mar 23 '23 20:03

Tom


2 Answers

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.

like image 162
wim Avatar answered Apr 10 '23 15:04

wim


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
like image 33
Burhan Khalid Avatar answered Apr 10 '23 13:04

Burhan Khalid