Ad

Take List Of List As Input In Python

- 1 answer

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.

Example:

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

Input :

a = [[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]

Output :

[['0', '4'], ['1', '2'], ['5', '7'], ['6', '7'], ['6', '9'], ['8', '1']]

Ad

Answer

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]]
Ad
source: stackoverflow.com
Ad