Reputation: 109
I need to take a input which will strictly be in the format [[a,b], [c,d], ... ]
, that is a list containing multiple lists. All the inner list will be containing two integer items.
a = [[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]
Problem is When I am passing this as an input it is bring converted to a string and then I am using this program to get the desired output but I am unable to make it work properly.
def l2l(li):
li = li.split(',', ' ')
out= []
for i in li:
try:
int(i)
out.append(i)
except ValueError:
pass
print(out)
out = list([out[i], out[i+1]] for i in range(0,len(out)-1,2))
return out
a = [[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]
[['0', '4'], ['1', '2'], ['5', '7'], ['6', '7'], ['6', '9'], ['8', '1']]
Upvotes: 0
Views: 108
Reputation: 2189
Use python's built in eval
function:
def l2l(li):
li = eval(li)
out= []
for i in li:
try:
out.append(i)
except ValueError:
pass
print(out)
out = list([out[i], out[i+1]] for i in range(0,len(out)-1,2))
return out
a = '[[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]'
l2l(a)
Out:
[[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]
Upvotes: 0
Reputation: 2492
Use the Python module ast
to convert it to a literal.
import ast
a = "[[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]"
lol = ast.literal_eval(a)
print("({}){}".format(type(lol), lol))
OUTPUT:
(<class 'list'>)[[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]
Upvotes: 3