How can I solve this "[[1,2,3],[3,4,5]]" = [[1,2,3],[3,4,5]] (from str to int) ?

M
Mahfuj (690 points)
1 2 3
asked Nov 15, 2021 in News by Mahfuj (690 points)
v="[[1,2,3],[3,4,5]]"

i used  int(v) but it's not working it shows

ValueError: invalid literal for int() with base 10: '[[1,2,3],[3,4,5]]'

is there any way to turn '[[1,2,3],[3,4,5]]'  to [[1,2,3],[3,4,5]] ?
141 views

1 Answer

Quellocinese (2700 points)
2 4 22
answered Nov 15, 2021 by Quellocinese (2,700 points)
First of all, how did you get a string o lists...

the int() casting works on literals that can be converted like "1" or "2" --> 1 or 2

you should't make the list of lists into a string so you can work with the the 2d array waaaaay more easily by looping through each element of each list in the matrix to cast the single values to int.

But i see that the lists you have in the string in v are already in int() type, so I suggest you to take the lists you generated and NOT put them in a string variable.
M
Mahfuj (690 points)
1 2 3
commented Nov 15, 2021 by Mahfuj (690 points)
reshown Nov 15, 2021 by Mahfuj
lines2=[[1, 2, 3],[3, 4, 5]]

v=''.join(str(lines2).split(' '))

I did this for removing the whitespace from lines2 then v turns into string

I am trying to print(v[0]) it gives '[' not [1,2,3]

but my fact is not that my question is" Is it possible to turn '[[1,2,3],[3,4,5]]'  to [[1,2,3],[3,4,5]] ?" ( Yes or Not )
andrea.sterbini (172680 points)
511 927 1776
commented Nov 15, 2021 by andrea.sterbini (172,680 points)
possibly by using the builtin function eval
Exyss (21390 points)
1 2 79
commented Nov 16, 2021 by Exyss (21,390 points)
You can either use the eval( ) method as the professor said or you can make your own parsing function, which however would probably get more complex/slow
andrea.sterbini (172680 points)
511 927 1776
commented Nov 16, 2021 by andrea.sterbini (172,680 points)
we will see how to write a recusive parser for this kind of expressions in december