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

Python嵌套循环生成Ursina体素坐标写入CSV仅存最后值问题

问题根因

故障是两个低级逻辑错误叠加导致的:

  1. 你只在循环外定义了1个terrain_dictionary字典对象,三层循环每次迭代都是直接修改这个字典的键值,上一次迭代写入的坐标会被下一次直接覆盖,循环结束后字典里自然只剩最后一次迭代的坐标(9.0,-2.0,9.0)。
  2. 写入CSV时你调用的是单行写入方法writerow(),传入的是被反复覆盖的单个字典,自然只能写出1条数据。
错误逻辑参考
# 问题写法示意
terrain_dictionary = {} # 全局只创建1个字典
for z in range(10):
    for y in range(3):
        for x in range(10):
            Voxel(position=(x,-y,z)) # 原有生成逻辑正常
            # 反复修改同一个字典的键值,覆盖历史数据
            terrain_dictionary["Object"] = "Cube"
            terrain_dictionary["x"] = x
            terrain_dictionary["y"] = -y
            terrain_dictionary["z"] = z

with open("position.csv","w") as f:
    writer = csv.DictWriter(f, fieldnames=["Object","x","y","z"])
    writer.writeheader()
    writer.writerow(terrain_dictionary) # 单行写入,只写最后剩下的1条
正确实现方案

核心修改点:

  • 用列表存储所有体素条目,不要复用单个字典
  • 每次循环新建独立字典存储当前体素信息,追加到列表
  • 写入时调用多行写入方法writerows()传入完整列表
import csv
from ursina import *

app = Ursina()
terrain_z_x = 10
terrain_depth = 3
terrain_records = [] # 初始化空列表存所有体素数据

for z in range(terrain_z_x):
    for y in range(terrain_depth):
        for x in range(terrain_z_x):
            # 保留原有体素生成逻辑
            Voxel(position=(x, -y, z))
            # 每次循环新建独立字典,避免覆盖
            record = {
                "Object": "Cube",
                "x": float(x),
                "y": float(-y),
                "z": float(z)
            }
            terrain_records.append(record)

# 批量写入CSV
with open("position.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["Object", "x", "y", "z"])
    writer.writeheader()
    writer.writerows(terrain_records) # 注意方法名带s,用于批量写多行

app.run()
效果验证

运行后生成的CSV会包含全部300条记录,坐标范围从(0.0, 0.0, 0.0)到(9.0, -2.0, 9.0),和预期完全一致。代码中newline=""是Python csv模块官方要求的参数,可避免Windows系统下写入时出现多余空行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 17:36:28