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

如何将空格分隔的坐标数字字符串转换为坐标元组列表?

实现空格分隔数字字符串转坐标元组列表

方法一:利用切片与zip快速实现

# 原始坐标字符串
coord_str = "50 5 10 4 48 34"

# 1. 将字符串分割为单个数字的字符串,再转换为整数列表
num_list = list(map(int, coord_str.split()))

# 2. 按奇偶索引分组配对,生成坐标元组列表
coords = list(zip(num_list[::2], num_list[1::2]))

print(coords)
# 输出结果:[(50, 5), (10, 4), (48, 34)]

方法二:循环遍历分组(更直观)

如果需要更清晰的逻辑展示,也可以用循环按步长2遍历整数列表,逐个生成坐标元组:

coord_str = "50 5 10 4 48 34"
num_list = list(map(int, coord_str.split()))
coords = []

# 从索引0开始,每次步进2,取当前索引和下一个索引的元素组成元组
for i in range(0, len(num_list), 2):
    coords.append((num_list[i], num_list[i+1]))

print(coords)
# 输出结果:[(50, 5), (10, 4), (48, 34)]

关键说明

  • split()方法默认会按任意空白字符(空格、换行等)分割字符串,无需额外处理多余空格;
  • num_list[::2]提取列表中所有偶数索引的元素(对应x坐标),num_list[1::2]提取奇数索引的元素(对应y坐标);
  • zip()函数会将两个列表中对应位置的元素配对,最终转换为列表即可得到目标格式。

内容的提问来源于stack exchange,提问作者Дмитрий Насонов

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 01:01:01