mariatsamp
mariatsamp

Reputation: 47

read input from command line store it into a 2d array, not as as string input

with open(sys.argv[1], 'r') as f:                  
    a= f.readlines()    #reads the file's lines
    a = [x.strip() for x in a] #ignores the newline char
print (a)

With this function, when I print the array, I have as an output this:

['+X..XX....-', '.X..X..X-..', '.X.........', '...XX......', 'XXX.+X.....', '..X.....XXX', '...XXX..X-.', '.-.....X...']

How can I convert the above function so as it returns

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

something like this, an array of elements instead an array of strings

Upvotes: 0

Views: 170

Answers (1)

G_M
G_M

Reputation: 3372

In[3]: with open('test.txt', 'r') as f:
  ...:     result = [list(line.rstrip()) for line in f]
  ...: 
In[4]: result
Out[4]: 
[['+', 'X', '.', '.', 'X', 'X', '.', '.', '.', '.', '-'],
 ['.', 'X', '.', '.', 'X', '.', '.', 'X', '-', '.', '.'],
 ['.', 'X', '.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', 'X', 'X', '.', '.', '.', '.', '.', '.'],
 ['X', 'X', 'X', '.', '+', 'X', '.', '.', '.', '.', '.'],
 ['.', '.', 'X', '.', '.', '.', '.', '.', 'X', 'X', 'X'],
 ['.', '.', '.', 'X', 'X', 'X', '.', '.', 'X', '-', '.'],
 ['.', '-', '.', '.', '.', '.', '.', 'X', '.', '.', '.']]

Upvotes: 3

Related Questions