user2975079
user2975079

Reputation: 21

Turning a List into an array of arrays in python

So I have an input text file that looks like this:

0,0,0,0  
0,0,1,0  
0,1,0,0  
0,1,1,1  
1,0,0,0  
1,0,1,0  
1,1,0,1  
1,1,1,1  

I have successfully read all of these lines into a list which looks like this:

['0,0,0,0' , '0,0,1,0' , '0,1,0,0' , '0,1,1,1' , '1,0,0,0' , '1,0,1,0' , '1,1,0,1', '1,1,1,1'] 

My code for creating this list is

fileName = input("Filename:")
    file = open(fileName,'r')
    training = np.array(file.read().splitlines())
    for i in range(len(training)):
        a.append(training[i])

However I was wondering how I can turn the list into something that looks like this:

[ [0,0,0,0] , [0,0,1,0] , [0,1,0,0] , [0,1,1,1] , [1,0,0,0] , [1,0,1,0] , [1,1,0,1] , [1,1,1,1] ]

If it is not clear, my list has value of type string but I want the type to be in int as well as in the format above.

Please let me know if there is a way I can get this end result through changing my code or somehow doing some sort of conversion.

Upvotes: 0

Views: 676

Answers (5)

Udit Bhayana
Udit Bhayana

Reputation: 1

What you can do is grab each element of the array and then each element of the string.

Eg. You can first grab '0,0,0,0' split by ',' and add each 0 to an array.. after getting n arrays, you can add them all to a single array.

P.S. you may want to confer the strings to int before you add them to an array, and should consider doing that once you've grabbed each 0 separately!

Upvotes: 0

Debdut Goswami
Debdut Goswami

Reputation: 1379

fileName = input("Filename:")
with open(fileName) as f:
    lines = f.readlines()
arr=list()
for line in lines:
    arr.append(list(map(int, line.rstrip().split(","))))

Here arr is your desired list of lists. What I am doing is reading the file lines and storing it in lines then, iterating through lines and spiting each line by , and then mapping them as int. If you do not perform the map function, then it will be str.

Note I am using rstrip() to remove the trailing new line character.

Upvotes: 1

Mazen
Mazen

Reputation: 58

You can use the following approach

training_arr = []
fileName = input("Filename:")
with open(fileName,'r') as fileName:
    training_arr = [[int(numeric_string) for numeric_string in line.split(',')] for line in fileName.readlines()]

print(training_arr)

Upvotes: 1

Pedro Lobito
Pedro Lobito

Reputation: 98931

You can also use:

with open("input.txt") as f:
    l = [[int(x) for x in x.split(",")] for x in f]

[[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 0, 1], [1, 1, 1, 1]]

Demo

Upvotes: 1

a_guest
a_guest

Reputation: 36279

You can split the strings on , and then convert to int:

a = [[int(n) for n in x.split(',')] for x in a]

Upvotes: 1

Related Questions