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

Python嵌套循环输出行列对齐问题:风寒温度表格格式化

解决风寒温度对齐表格生成问题

需求:根据给定的温度和风速列表计算风寒温度,生成Y轴为温度、X轴为风速的对齐表格。

现有代码存在表头与内容列宽不统一、温度行前缀格式混乱、无效判断逻辑干扰输出等问题,导致表格错位。

修正后的代码

windspeed = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
temperature = [-20, -10, 0, 10, 20, 30, 40, 50, 60]

# 打印表头行,明确Y轴为温度
print("|{0:^6}|".format("Temp"), end='')
for ws in windspeed:
    print("{0:^8}|".format(ws), end='')
print()

# 打印分隔线,区分表头与内容
print("|{0:-<6}|".format(''), end='')
for _ in windspeed:
    print("{0:-<8}|".format(''), end='')
print()

# 逐行计算并打印风寒温度
for temp in temperature:
    # 格式化温度列,与表头对齐
    print("|{0:^6}|".format(temp), end='')
    for ws in windspeed:
        # 计算风寒温度:风速>3时用公式,否则等于当前温度
        if ws > 3:
            windchill = 35.74 + 0.6215 * temp - 35.75 * (ws ** 0.16) + 0.4275 * temp * (ws ** 0.16)
        else:
            windchill = temp
        # 统一单元格格式:居中对齐、固定宽度8、保留两位小数
        print("{0:^8.2f}|".format(windchill), end='')
    print()

改进说明

  1. 统一格式标准:所有单元格采用固定宽度和居中对齐,彻底解决行列错位问题
  2. 优化表头结构:增加"Temp"列标注Y轴含义,添加分隔线提升可读性
  3. 简化冗余逻辑:移除无效的row == 1判断(温度列表无此值)
  4. 输出Markdown表格:直接生成可在Markdown环境中渲染的规整表格,输出示例如下:
Temp05101520253035404550
-20-20.00-32.78-39.42-43.67-46.94-49.61-51.88-53.85-55.59-57.15-58.56
-10-10.00-22.41-28.83-32.92-36.06-38.63-40.82-42.72-44.39-45.88-47.23
00.00-12.05-18.24-22.17-25.19-27.65-29.76-31.60-33.23-34.68-35.99
1010.00-1.68-7.65-11.43-14.31-16.70-18.75-20.54-22.12-23.53-24.80
2020.008.693.03-0.99-3.84-6.17-8.15-9.87-11.38-12.72-13.93
3030.0019.0613.719.526.403.901.850.10-1.48-2.89-4.16
4040.0029.4324.3920.0716.9114.2312.0610.248.737.456.34
5050.0039.8035.0830.6227.4224.5722.2720.3918.8817.6116.52
6060.0050.1745.7641.1737.9434.9032.4830.5329.0327.7726.70

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:47:02