如何解构python中的字符串数据?

How to deconstruct string data in python?

>>> st['xy'][0]
>>> '(35.25792753, 129.2127994)'
>>> filled['xy'][0]
>>> (37.77432579, 128.9071418)

我需要 ( x , y ) 数据格式而不是 '( x , y ) ' 来使用半正弦函数。

如何解构字符串数据?

看起来你的数据是一个字符串。如果它的格式始终与显示的格式类似,您可以执行以下操作:

data = st['xy'][0]
x, y = data.split(" ")
x, y = float(x[1:-1]), float(y[:-1])  # Slice parentheses and comma away

也可以使用正则表达式(这种方法比较通用):

import re
data = st['xy'][0]
number_pattern = r'\d+(?:\.\d+)'
x, y = re.findall(number_pattern, data)  # NB: Will error out if your string is not well-formatted

您可以使用内置模块,re:

import re

t = tuple(re.findall("\d+\.\d+", st['xy'][0]))

使用ast.ast_literal

ast.literal 提供从字符串安全构造对象(即比 eval 更安全)

import ast
value = ast.literal_eval(st['xy'][0])

# value becomes tuple: (35.25792753, 129.2127994)