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

前端 未结 3 677
不思量自难忘°
不思量自难忘° 2020-12-11 22:14

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 doe

3条回答
  •  悲&欢浪女
    2020-12-11 22:57

    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.

提交回复
热议问题