1

I have a text file like this:

0 0 1
1 1 1
1 0 1
0 1 0

And i would like to get a 2D array like this:

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

I have tried:

with open("Input_Data.txt", "r") as txt_file:
    input_data = [line.split() for line in txt_file]
print(input_data)

But it returns:

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

How could I get an array of int instead of string please?

3 Answers 3

4

Use this line of code:

input_data = [list(map(int, line.split())) for line in txt_file]

You got strings, but you wanted integers so you have to parse each string into an integer.

map will apply the function given as first argument to all elements in the second argument, and return an iterator. Then you consume that iterator by using list constructor.

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

Comments

1
with open("Input_Data.txt", "r") as txt_file:
    input_data = [[int(x) for x in line.split()] for line in txt_file]
print(input_data)

Comments

0

To complete answers, I add loadtxt function of numpy lib. It's very simple, output is a ndarray:

import numpy as np

my_array = np.loadtxt("Input_Data.txt", dtype="uint8", delimiter=' ')

You can specify data type, default is float.

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.