【问题标题】:How to deconstruct string data in python?如何在python中解构字符串数据?
【发布时间】:2020-06-06 22:19:36
【问题描述】:
>>> st['xy'][0]
>>> '(35.25792753, 129.2127994)'
>>> filled['xy'][0]
>>> (37.77432579, 128.9071418)

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

如何解构字符串数据?

【问题讨论】:

  • 你能扩展你的代码示例吗?目前尚不清楚 st 和填充的来源以及您使用的 hasrsine 实现。
  • 这些字符串的来源是什么? 是你的根本问题。你应该解决这个问题。

标签: python string haversine


【解决方案1】:

使用ast.ast_literal

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

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

# value becomes tuple: (35.25792753, 129.2127994)

【讨论】:

    【解决方案2】:

    看起来你的数据是一个字符串。如果它始终采用与所示格式相似的格式,您可以这样做:

    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
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2015-09-18
        • 2023-04-06
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-04
        相关资源
        最近更新 更多