0

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']]

4
  • Since that string happens to conform to the JSON format, you could use the module for that to parse the initial string. It should give you integers in the resulting object. Commented Oct 20, 2019 at 9:41
  • 1
    @Quroborus could you explain that? Commented Oct 20, 2019 at 9:46
  • @p.ram answered your question Commented Oct 20, 2019 at 10:00
  • Show the actual code where you call the function, please. Commented Oct 20, 2019 at 10:19

2 Answers 2

3

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, there is no need of the ast module. Try simply eval(a). It still works.
0

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]]

2 Comments

`li = eval(li) is enough to for the required answers?
Just understand that eval can be dangerous. it will on the fly evaluate whatever you pass it. so if its something that runs code to erase a directory, etc. that would not be good for someone using your code. I like the idea of using the json load string function better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.