0

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.

2

5 Answers 5

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Isn't having two variables named x like this potentially problematic?
Why do you say that?
1

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

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

Comments

1

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)

Comments

1
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.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.