简体   繁体   中英

Converting a string of tuples to a list of tuples in Python

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.

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 .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM