我正在尝试将看起来像这样的字符串转换为元组数组
"[(1,2), (2,3), (4,5)]"
- > [(1,2), (2,3), (4,5)]
以下是我想填充的代码体:
def convert_to_polygon(polygon_string):
return polygon_array
我应该使用python库吗?这项工作是否存在?
答案 0 :(得分:4)
您可以使用ast.literal_eval
:
>>> import ast
>>> s = '{{1,2},{2,3},{4,5}}'
>>> polygon_array = ast.literal_eval(s.replace('{', '(').replace('}', ')'))
>>> polygon_array
((1, 2), (2, 3), (4, 5))
>>> polygon_array[1][0]
2
如果需要元组列表,请使用list(polygon_array)
。
答案 1 :(得分:1)
>>> def convert_to_polygon(polygon_string):
... return eval(polygon_string)
...
>>> polygon_string = "[(1,2), (2,3), (4,5)]"
>>> convert_to_polygon(polygon_string)
[(1, 2), (2, 3), (4, 5)]