You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从坐标字符串数组提取x1、y1、x2、y2值(不使用外部库)

字符串坐标转数值变量解决方案

实现思路

无需外部库,通过手动解析每个坐标字符串即可完成转换:移除括号、拆分坐标分量、转换为整数类型。

代码实现

s = ['(2,-1)', '(2,2)']

# 解析第一个坐标
p1 = s[0].strip('()').split(',')
x1, y1 = int(p1[0]), int(p1[1])

# 解析第二个坐标
p2 = s[1].strip('()').split(',')
x2, y2 = int(p2[0]), int(p2[1])

# 验证结果
print(f"x1: {x1}, y1: {y1}")
print(f"x2: {x2}, y2: {y2}")

步骤说明

  • strip('()') 移除字符串首尾的括号,将 '(2,-1)' 转换为 '2,-1'
  • split(',') 按逗号拆分字符串,得到坐标分量列表,例如 ['2', '-1']
  • int() 将每个字符串分量转换为整数,分别赋值给对应变量

运行输出

x1: 2, y1: -1
x2: 2, y2: 2

内容的提问来源于stack exchange,提问作者amit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 17:55:58