如何在python中从文本文件读取和存储k,m和数据点

时间:2018-07-14 17:31:15

标签: python-3.x csv

我有一个文本文件,在第一行中包含k和m的值,从第二行开始,它包含所有m维数据点,如下所示:

class Person(val name: String) {
     companion object {
          @JvmStatic fun main(args: Array<String>) {
               val p = Person("me") 
               System.out.println(p.name);
          } 
     }
}

如何阅读和存储

5 4

1.6 0.3 15.0 14.1

1.3 9.1 0.9 12.4

5.6 9.9 14.4 18.6

25.0 1.3 12.9 2.1

17.2 3.4 9.2 14.7

2.3 2.2 1.2 9.5
.............

读取所有数据点后,我想对其执行最远的优先算法

1 个答案:

答案 0 :(得分:1)

您不需要多维空间-您只需要列表。

创建您的演示数据:

data = """5 4

1.6 0.3 15.0 14.1

1.3 9.1 0.9 12.4

5.6 9.9 14.4 18.6

25.0 1.3 12.9 2.1

17.2 3.4 9.2 14.7

2.3 2.2 1.2 9.5"""

fn = "file.txt"

with open(fn, "w") as f:
    f.write(data)

将其读回浮点数列表的合适数据结构中:

fn = "file.txt"
all_data = []
with open(fn,"r") as f:
    k,m = map(float,f.readline().strip().split())
    for line in f:
        if line.strip(): # weed out empties
            line = list(map(float,line.split()))
            all_data.append(line)

print("k:",k,"m:",m)
print(all_data)

给出以下输出:

k: 5.0 m: 4.0
[[1.6, 0.3, 15.0, 14.1],   # each line is one row of your data
 [1.3, 9.1, 0.9, 12.4],    # its position the same as in your file
 [5.6, 9.9, 14.4, 18.6],   # and you can use those in whatever calculations
 [25.0, 1.3, 12.9, 2.1],   # you need to do 
 [17.2, 3.4, 9.2, 14.7], 
 [2.3, 2.2, 1.2, 9.5]]

您已经在列表中找到了所有数字,可以从那里去。

如果您需要它们分别为xyzt,则可以使用zip()all_data收集它们并利用分解:

x,y,z,t = map(list,zip(*all_data))

print(x)
print(y)
print(z)
print(t)

输出:

[1.6, 1.3, 5.6, 25.0, 17.2, 2.3]   # x
[0.3, 9.1, 9.9, 1.3, 3.4, 2.2]     # y
[15.0, 0.9, 14.4, 12.9, 9.2, 1.2]  # z
[14.1, 12.4, 18.6, 2.1, 14.7, 9.5] # t

也使用:map()