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

在Jupyter Notebook中如何用Python从文本文件导入坐标到citylist列表

从cities8文件读取坐标到citylist的实现方法

先看你的文件内容(如下方图片所示),每行包含一组x、y坐标,可用以下两种方式实现需求:

cities8文件内容

方法一:基础文件读取方式

适合空格/制表符分隔的坐标格式,代码简洁直接:

citylist = []
# with语句会自动处理文件关闭,避免资源泄漏
with open('cities8.txt', 'r') as file:
    for line in file:
        # 去除行首尾空白字符,分割成坐标字符串
        coords = line.strip().split()
        # 跳过空行(如果文件里存在的话)
        if not coords:
            continue
        # 转换为数值类型,需要整数的话把float改成int
        x, y = float(coords[0]), float(coords[1])
        # 把坐标以元组形式添加到列表
        citylist.append((x, y))

方法二:使用csv模块(规范处理分隔文件)

如果坐标用逗号或其他固定分隔符分隔,用csv模块更稳妥:

import csv

citylist = []
with open('cities8.txt', 'r') as file:
    # 指定分隔符,你的文件是空格分隔就用' ',逗号分隔用','
    reader = csv.reader(file, delimiter=' ')
    # 如果文件有表头,先执行next(reader)跳过第一行
    for row in reader:
        if not row:
            continue
        x, y = float(row[0]), float(row[1])
        citylist.append((x, y))

执行完代码后,citylist就会存储所有读取到的坐标对。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:06:25