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

Python不使用pandas如何遍历分块嵌套列表每一列并为每列生成两个点

问题解答

第一部分:嵌套列表列遍历实现

你当前代码的问题在于:zip(*X) 会按所有子列表的最短长度进行配对,你给出的嵌套列表X中4个子列表长度分别为5、2、2、1,最短长度为1,因此只会返回索引为0的1组结果,也就是你看到的输出。

正确的实现有两种常用方式:

方式1:手动按索引遍历

max_col_count = max(len(sublist) for sublist in X)
for col_idx in range(max_col_count):
    current_col = []
    for sublist in X:
        if col_idx < len(sublist):
            current_col.append(sublist[col_idx])
    # 输出当前列内容
    print(current_col)

方式2:使用itertools.zip_longest

自动补全不同长度子列表的空缺位,默认填充None,再按需过滤即可:

from itertools import zip_longest
for col in zip_longest(*X):
    # 过滤掉空缺的None值
    valid_col = [point for point in col if point is not None]
    print(valid_col)

第二部分:按列生成两个点集

你嵌套列表中每个元素都是[x坐标, y坐标]的二维点结构,只需要在遍历到每一列后,拆分所有点的x、y维度即可得到两组点:

from itertools import zip_longest
for col_idx, col in enumerate(zip_longest(*X)):
    valid_col = [point for point in col if point is not None]
    # 拆分x、y两个点集
    x_points = [p[0] for p in valid_col]
    y_points = [p[1] for p in valid_col]
    print(f"第{col_idx+1}列 x点集合:{x_points}")
    print(f"第{col_idx+1}列 y点集合:{y_points}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:09:01