我有一个文件,其内容如下
14.678 14.652 14.636 14.623 14.615 14.608 14.603 14.599 14.596
17.448 17.427 17.413 17.402 17.395 17.390 17.386 17.384 17.382
18.271 18.252 18.240 18.231 18.223 18.217 18.212 18.211 18.209
20.239 20.216 20.198 20.188 20.168 20.164 20.165 20.147 20.125
20.500 20.480 20.458 20.438 20.421 20.400 20.382 20.368 20.355
17.195 17.173 17.159 17.150 17.143 17.138 17.134 17.132 17.130
18.652 18.628 18.611 18.600 18.590 18.583 18.580 18.571 18.565
18.721 18.697 18.684 18.673 18.665 18.656 18.648 18.645 18.644
19.501 19.452 19.396 19.314 19.166 18.936 18.629 18.325 18.089
18.470 18.449 18.434 18.421 18.413 18.406 18.401 18.399 18.397
18.288 18.266 18.254 18.245 18.237 18.232 18.229 18.228 18.227
18.691 18.669 18.653 18.641 18.631 18.622 18.614 18.612 18.606
17.407 17.387 17.375 17.366 17.360 17.355 17.352 17.349 17.348
16.691 16.672 16.659 16.649 16.643 16.639 16.635 16.632 16.631
19.293 19.271 19.253 19.244 19.233 19.226 19.218 19.209 19.201
18.530 18.509 18.493 18.482 18.474 18.469 18.463 18.457 18.452
18.769 18.742 18.725 18.712 18.701 18.695 18.688 18.682 18.681
18.356 18.335 18.320 18.310 18.300 18.294 18.288 18.283 18.281
18.332 18.313 18.298 18.286 18.280 18.276 18.271 18.267 18.265
14.998 14.977 14.963 14.953 14.945 14.940 14.936 14.933 14.930
我想从每个其他值中删除每个第一列值。操作应该是这样的
14.678 - 17.448
14.678 - 18.271
14.678 - 18.271
and so on...
类似地
17.448 - 14.678
17.448 - 18.271
17.448 - 20.239
and so on...
到目前为止,我能够做的是
with open("geodata.txt", "r") as fo:
for i in fo:
for j in fo:
print(float(i.split(" ")[0]) - float(j.split(" ")[0]))
但它只进行一次操作然后停止。
-2.7699999999999996
-3.593
-5.561
-5.821999999999999
-2.5169999999999995
-3.974
-4.042999999999999
-4.823
-3.791999999999998
-3.6099999999999994
-4.012999999999998
-2.728999999999999
-2.012999999999998
-4.614999999999998
-3.8520000000000003
-4.0909999999999975
-3.678000000000001
-3.654
-0.3199999999999985
我尝试添加一个while循环来执行此操作20次(有20行)但计算需要永远。我怎样才能实现此目的?
答案 0 :(得分:0)
使用Python内置的CSV库,可以按照以下方式完成:
import csv
with open('geodata.txt', 'r', newline='') as f_input, open('output.csv', 'w', newline='') as f_output:
csv_input = csv.reader(f_input, delimiter=' ', skipinitialspace=True)
csv_output = csv.writer(f_output, delimiter=' ')
first_row = list(map(float, next(csv_input)))
for row in csv_input:
new_row = [first_value - float(value) for first_value, value in zip(first_row, row)]
csv_output.writerow(new_row)
给你一个output.csv
文件开头:
-2.7699999999999996 -2.7750000000000004 -2.777000000000001 -2.7790000000000017 -2.7799999999999994 -2.782 -2.7829999999999995 -2.785 -2.7860000000000014
-3.593 -3.5999999999999996 -3.603999999999999 -3.6080000000000023 -3.6079999999999988 -3.608999999999998 -3.609 -3.6119999999999983 -3.6129999999999995
-5.561 -5.564000000000002 -5.562000000000001 -5.5649999999999995 -5.552999999999999 -5.556000000000001 -5.561999999999999 -5.547999999999998 -5.529