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

Python列表处理:拆分含坐标元组的嵌套列表为x、y坐标列表

实现方法

方法1:Python原生实现(无需依赖第三方库)

直接用两层列表推导式遍历嵌套结构,分别提取每个坐标元组的x、y值,可适配任意数量的bin和坐标点:

# 你的原始输入数据
list_of_list = [[(2,1),(4,2),(3,1)], [(1,1),(2,2),(4,3)]]

# 拆分x、y轴数值
x = [[coord[0] for coord in single_bin] for single_bin in list_of_list]
y = [[coord[1] for coord in single_bin] for single_bin in list_of_list]

运行后输出的x、y完全符合你要求的格式。

方法2:Numpy实现(适合大数据量、多层嵌套场景)

如果你的数据规模较大、嵌套层级更多,用Numpy的索引语法会更简洁,扩展性更强:

import numpy as np

# 转换为Numpy数组
data_arr = np.array(list_of_list)
# 提取最后一维的第0位为x值,第1位为y值,自动适配前面的所有嵌套层级
x = data_arr[..., 0].tolist()
y = data_arr[..., 1].tolist()

额外优化:直接生成Mathematica兼容格式

如果你需要直接输出可以复制到Mathematica中使用的格式,不需要手动替换括号,可以加一行格式转换:

def to_mathematica_list(py_list):
    return str(py_list).replace("[", "{").replace("]", "}")

print(f"x = {to_mathematica_list(x)}")
print(f"y = {to_mathematica_list(y)}")

输出结果直接对应Mathematica的列表语法,可直接导入使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 01:21:03