Please ignore secret bonuses. Secret tests do NOT award bonus. Max hw grade is 30+2 bonus efficiency

Do you need help?

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
in News by (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]] ?
342 views

1 Answer

Quellocinese (2700 points)
4 4 22
by (2.7k 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
by (690 points)
reshown by
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 (207940 points)
756 1270 2377
by (208k points)
possibly by using the builtin function eval
Exyss (21510 points)
1 2 79
by (21.5k 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 (207940 points)
756 1270 2377
by (208k points)
we will see how to write a recusive parser for this kind of expressions in december