【发布时间】:2019-07-31 00:01:06
【问题描述】:
我正在尝试将以下文件中的行读入 3 个列表,其中第二列(读取到 2 个小数位)包含 x 值,第三列包含 y 值。当行号(第一列)从一个开始时,我想要一个新列表。
1 0.05 0
2 0.1 0
3 0.15 0
4 0.2 0
5 0.25 0
6 0.3 0
7 0.35 0
8 0.4 1
9 0.45 1
10 0.5 2
11 0.55 3
12 0.6 4
13 0.65 5
14 0.7 6
15 0.75 7
16 0.8 8
17 0.85 8
18 0.9 9
19 0.95 10
20 1 11
1 0.047619 0
2 0.0952381 1
3 0.142857 1
4 0.190476 1
5 0.238095 1
6 0.285714 1
7 0.333333 1
8 0.380952 1
9 0.428571 1
10 0.47619 1
11 0.52381 2
12 0.571429 3
13 0.619048 4
14 0.666667 5
15 0.714286 5
16 0.761905 5
17 0.809524 6
18 0.857143 7
19 0.904762 8
20 0.952381 8
21 1 9
1 0.0526316 0
2 0.105263 0
3 0.157895 0
4 0.210526 0
5 0.263158 1
6 0.315789 1
7 0.368421 1
8 0.421053 1
9 0.473684 2
10 0.526316 3
11 0.578947 3
12 0.631579 3
13 0.684211 4
14 0.736842 5
15 0.789474 5
16 0.842105 6
17 0.894737 7
18 0.947368 8
19 1 9
我有以下代码。当我去绘制它们时,只绘制了 x1 和 y1。起初我认为这是我的绘图代码的问题,但是当我单独绘制它们时,我发现列表 x2、y2、x3、y3 是空的,这让我相信这些列表没有正确读取值。
import numpy as np
import matplotlib.pyplot as plt
with open('kmt_oa.txt') as f:
lines1 = f.readlines()[0:20]
x1 = [line.split()[1][:4] for line in lines1]
y1 = [line.split()[2] for line in lines1]
lines2 = f.readlines()[21:40]
x2 = [line.split()[1][:4] for line in lines2]
y2 = [line.split()[2] for line in lines2]
lines3 = f.readlines()[41:60]
x3 = [line.split()[1][:4] for line in lines3]
y3 = [line.split()[2] for line in lines3]
ax1 = plt.subplot()
ax1.scatter(x1, y1, color = 'r', label = 'Table size of 20')
ax1.scatter(x2, y2, color = 'g', label = 'Table size of 21')
ax1.scatter(x3, y3, color = 'b', label = 'Table size of 19')
ax1.set_xlabel('Load Factor')
ax1.set_ylabel('Number of Collisions')
ax1.set_title("Key Mod Tablesize & Open Addressing")
ax1.set_ylabel('Number of Collisions')
plt.legend(loc = 'upper left')
plt.show()
【问题讨论】:
标签: python list file input formatting