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

Python程序信息排序异常,求修复地块面积数据排序功能方案

问题修复方案

你代码的核心错误点如下:

  • 读取的地块号文件内容没有存入变量,整个排序逻辑的数据源为空
  • 冒泡排序仅交换了面积值,没有交换整个[地块号, 面积]子项,导致地块和面积对应关系错乱
  • 仅请求了单次地块面积,没有批量遍历所有地块号拉取数据
  • 排序用的列表构造逻辑混乱,没有正确关联地块号和对应面积

修改后的完整可运行代码如下:

import json
import requests
import csv

# 1. 读取所有地块号
with open('katastritunnused.txt', 'r', encoding='utf-8') as f:
    # 按行读取,过滤空行和首尾空白字符
    plot_ids = [line.strip() for line in f if line.strip()]

# 2. 批量拉取所有地块的面积数据
plot_data = []
for plot_id in plot_ids:
    try:
        url = f'https://geoportaal.maaamet.ee/url/xgis-ky.php?ky={plot_id}&out=json'
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        json_response = response.json()
        # 提取面积转成数值类型,避免字符串比较导致排序错误
        area = float(json_response["1"].get("Pindala", 0))
        plot_data.append([plot_id, area])
    except Exception as e:
        print(f"地块{plot_id}数据拉取失败:{e}")
        continue

# 3. 修复冒泡排序逻辑
def bubblesort(data):
    n = len(data)
    for _ in range(n):
        jarjestatud = True
        for x in range(n - _ - 1):
            if data[x][1] > data[x + 1][1]:   
                # 交换整个子列表,保证地块号和面积的对应关系不错乱
                data[x], data[x + 1] = data[x + 1], data[x]
                jarjestatud = False
        if jarjestatud:
            break
    return data

# 4. 排序处理,需要升序就删掉reverse行
sorted_data = bubblesort(plot_data)
sorted_data.reverse()

# 5. 导出CSV,用标准库避免格式错误
def write_to_csv(data, file_path='sorteeritud.csv'):
    with open(file_path, mode='w', encoding='utf-8', newline='') as csv_file:
        writer = csv.writer(csv_file, delimiter=';')
        # 可选添加表头,不需要可以注释掉
        writer.writerow(['地块号', '面积'])
        for item in data:
            writer.writerow(item)

write_to_csv(sorted_data)

关键修改说明

  • 补全了地块号文件的读取逻辑,所有有效地块号会存入列表批量处理
  • 修正了冒泡排序的交换逻辑,保证地块号和对应面积始终绑定不会错位
  • 增加了异常捕获,避免单个地块拉取失败导致整个程序崩溃
  • 改用Python标准csv库写文件,避免手动拼接字符串出现格式问题
  • 面积提前转成数值类型,避免字符串比较导致的排序逻辑错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:15:08