3

How can I convert "[(5, 2), (1,3), (4,5)]" into a list of tuples [(5, 2), (1,3), (4,5)]

I am using planetlab shell that does not support "import ast". So I am unable to use it.

5
  • 5
    For the 1230123012312th time: ast.literal_eval Commented Oct 28, 2011 at 22:53
  • @JBernardo: Maybe that should be an answer? Commented Oct 28, 2011 at 22:54
  • I am using planetlab shell that does not support "import ast". SO I am unable to use it. Commented Oct 28, 2011 at 22:57
  • possible duplicate of convert a list of strings that i would like to convert to a list of tuples Commented Oct 28, 2011 at 22:57
  • 1
    @Parikshit Then a plain eval won't help you? Commented Oct 28, 2011 at 22:58

3 Answers 3

5

If ast.literal_eval is unavailable, you can use the (unsafe!) eval:

>>> s = "[(5, 2), (1,3), (4,5)]"
>>> eval(s)
[(5, 2), (1, 3), (4, 5)]

However, you should really overthink your serialization format. If you're transferring data between Python applications and need the distinction between tuples and lists, use pickle. Otherwise, use JSON.

Sign up to request clarification or add additional context in comments.

2 Comments

I see if s = "[('a', 2), ('b',3), ('c',5)]" result is [(a, 2), (b, 3), (c, 5)]
@Slim_user71169 That's not true in any Python I know of. Can you post a link to an online interpreter that shows the problem, like this?
1

If you don't trust the source of the string enough to use eval, then use re.

import re
tuple_rx = re.compile("\((\d+),\s*(\d+)\)")
result = []
for match in tuple_rx.finditer("[(5, 2), (1,3), (4,5)]"):
  result.append((int(match.group(1)), int(match.group(2))))

The code above is very straightforward and only works with 2-tuples of integers. If you want to parse more complex structures, you're better off with a proper parser.

Comments

1

'join' replace following characters '()[] ' and creates string of comma separated numbers

5,2,1,3,4,5

'split' splits that string on ',' and creates list strings

['5','2','1','3','4','5']

'iter' creates iterator that will go over list of elements

and the last line uses a list comprehension using 'zip' to group together two numbers

it = iter("".join(c for c in data if c not in "()[] ").split(","))
result = [(int(x), int(y)) for x, y in zip(it, it)]

>>> [(5, 2), (1, 3), (4, 5)]

Comments

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.