How to import a string file into a list of lists?

I basically have a text file:

-1 2 0 0 0 0 0 2 -1 -1 -2 0 0 -2 2 0 1 0 

Who do I want to put on the list of lists so that it looks like this:

 [[-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 creates a list of strings in 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]) 

This creates [['-1,2,0'],['0,0,0'],['0,2,-1'],['-1,-2,0'],['0,-2,2'],['0,1,0']] This is almost what I want, except for quotation marks.

+4
source share
5 answers

A simple solution without additional libraries

 import os lines = [] f = open(os.path.expanduser("~/Desktop/example board.txt")) for line in f: x = [int(s) for s in line.split()] lines.append(x) 

Output:

 [[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]] 
0
source

I would recommend just using numpy for this, rather than reinventing 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 find a numpy array that will become a more useful data structure than a list of lists.

+4
source

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 
+2
source

This should do the trick, as it seems like you want the data to be numbers, not strings:

 fin = open('example.txt','r') # The list we want list_list = [] for line in fin: # Split the numbers that are separated by a space. Remove the CR+LF. numbers = line.replace("\n","").split(" ") # The first list list1 = [] for digit in numbers: list1.append(int(digit)) # The list within the list list_list.append(list1) fin.close() 

This creates the following conclusion:

 [[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]] 
+1
source

If you have comma separated values, csv is often the best choice. If this does not work, for some reason, then you can do only with lines and lists of built-in modules.

You can do all this in a list comprehension:

 with open('~/Desktop/example board.txt', 'r') as fin: lines = [[int(column.strip()) for column in row.split(',')] for row in fin] 

But it is opaque and can be remodeled:

 def split_fields(row): fields = row.split(',') return [int(field.strip()) for field in fields] with open('~/Desktop/example board.txt', 'r') as fin: lines = [split_fields(row) for row in fin] 
0
source

Source: https://habr.com/ru/post/1482305/


All Articles