Python Forum
Convert element of list to integer(Two dimentional array) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Convert element of list to integer(Two dimentional array) (/thread-10876.html)



Convert element of list to integer(Two dimentional array) - zorro_phu - Jun-11-2018

I'm trying to learn arrays(with numpy) in python3 but i am not able to figure out how do i convert the elements of list to integer(in my case i have two dimentional array). I've tried two solutions that i found(its mentioned in the code) but it gives me error. Can someone help me? Thank you.
My main objective is to get inputs and store them like a matrix(for example like 3x3) so that later i can take any elements of the list and perform any operation on them.
[inline]
from numpy import array

r,c=input("Number of row and cloumn:").split('x')
r=int(r)
c=int(c)
m=[]

for i in range(r):
    row_col=input("Row values:").split()
    m.append(row_col)
    
m=list(map(int,m)) #not working
# m=[int(i) for i in m] not working

m=array(m)
print(m)
print(m[0:1,0:1])
[/inline]

Output:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
If i dont use the conversion( m=list(map(int,m)) ) then i get
Output:
Number or row and cloumn:3x3 Row values:1 2 3 Row values:4 5 6 Row values:7 8 9 [['1' '2' '3'] ['4' '5' '6'] ['7' '8' '9']] [['1']]
My expected output
Output:
Row values:1 2 3 Row values:4 5 6 Row values:7 8 9 [[1, 2, 3] [4, 5, 6] [7, 8, 9]] [[1]]



RE: Convert element of list to integer(Two dimentional array) - killerrex - Jun-11-2018

You need to transform each row first to integer, either when you read the values:
for i in range(r):
    row = input("Row values:")
    m.append([int(s) for s in row.split()])
Or later:
m = [[int(s) for s in row] for row in m]
Remember that numpy only transforms a matrix given as a list of lists to a 2D array if all the lists have the same number of elements, so you might want to use the c value that you are not using to guarantee that the user inputs the right number of elements (or to add 0 or truncate as needed)


RE: Convert element of list to integer(Two dimentional array) - Larz60+ - Jun-11-2018

Or you could use the following which will allow mixed numbers and strings:
>>> mylist = ['1', '4', '6', '8', 'hello', '7']
>>> newlist = [int(item) if item.isdigit() else item for item in mylist]
>>> newlist
[1, 4, 6, 8, 'hello', 7]
>>>



RE: Convert element of list to integer(Two dimentional array) - zorro_phu - Jun-12-2018

Thanks a lot. I'll try all the solutions.