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

如何用Python将文本文件数字序列转为两列数组并按奇偶位绘制XY图?

用Python实现奇数/偶数位置数字的XY绘图

没问题,这需求用Python处理起来很简单,我给你一套完整的实现方案,包含数据读取、处理和绘图全流程:

第一步:准备依赖

我们需要用到 matplotlib 来绘图,如果你的环境还没装,先执行安装命令:

pip install matplotlib

(如果需要更高效的数组处理,也可以装 numpy,不过纯Python列表也能搞定)

第二步:读取并解析文本文件

首先要把test.txt里的数字序列读出来,转换成整数列表。考虑到文件里的数字可能带空格(比如2, 5, 6),我们先把空格去掉再分割:

# 读取文件并处理成整数列表
with open('test.txt', 'r') as file:
    # 读取内容、去掉首尾空白、替换所有空格为空
    raw_content = file.read().strip().replace(' ', '')
    # 按逗号分割成字符串,再转成整数列表
    num_list = list(map(int, raw_content.split(',')))

第三步:拆分X/Y轴数据

注意你说的「奇数位置」是日常计数的第1、3、5...位,对应Python列表的0、2、4...索引(因为Python从0开始计数);「偶数位置」是第2、4、6...位,对应索引1、3、5...。我们用切片就能快速拆分:

# 处理数据长度为奇数的情况(避免最后一个X没有对应Y)
if len(num_list) % 2 != 0:
    num_list = num_list[:-1]  # 移除最后一个多余的数字

# 拆分X(奇数位置)和Y(偶数位置)
x_data = num_list[::2]  # 从索引0开始,步长2取数
y_data = num_list[1::2] # 从索引1开始,步长2取数

第四步:绘制关系图

用matplotlib可以轻松绘制散点图或者折线图,这里以散点图为例(如果要折线图,把scatter换成plot即可):

import matplotlib.pyplot as plt

# 创建绘图对象
plt.figure(figsize=(8, 6))

# 绘制散点图,设置颜色和标签
plt.scatter(x_data, y_data, color='#2ecc71', s=50, alpha=0.7, label='Data Points')

# 添加图表元素
plt.xlabel('X-axis (Odd Positions)', fontsize=12)
plt.ylabel('Y-axis (Even Positions)', fontsize=12)
plt.title('Relationship Between Odd & Even Positioned Numbers', fontsize=14, pad=15)
plt.legend()
plt.grid(True, linestyle='--', alpha=0.5)

# 显示图表
plt.show()

可选:用Numpy简化处理

如果你的数据量很大,用numpy处理数组会更高效,代码如下:

import numpy as np
import matplotlib.pyplot as plt

# 读取并转成numpy数组
with open('test.txt', 'r') as file:
    raw_content = file.read().strip().replace(' ', '')
    num_array = np.array(list(map(int, raw_content.split(','))))

# 处理奇数长度
if num_array.size % 2 != 0:
    num_array = num_array[:-1]

# 拆分X/Y
x_np = num_array[::2]
y_np = num_array[1::2]

# 绘图(和之前逻辑一致)
plt.scatter(x_np, y_np, color='#3498db')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

这样就能完美实现你的需求啦,运行代码后就能看到X轴是原序列奇数位置的数字,Y轴是偶数位置数字的关系图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:33:03