问题描述
我最近开始使用Python,现在遇到类似于以下的问题。 我有一个txt文件,其中行没有相同数量的值:
who you gonna call 555 2368
56 20 9 7 8
0 9 7 -789 -9
-19 -14 0 9 0
0 -1 0 9 0
-4.0 -4.1 -4.2 -4.3 -4.4
-5.0 -5.1 -5.2 -5.3 -5.4
-6.0 -6.1 -6.2 -6.3 -6.4
-7.0 -7.1 -7.2 -7.3 -7.4
+1.0 +1.1 +1.2 +1.3 +1.4
+2.0 +2.1 +2.2 +2.3 +2.4
+3.0 +3.1 +3.2 +3.3 +3.4
+4.0 +4.1 +4.2 +4.3 +4.4
-6.0 -6.1 -6.2 -6.3 -6.4
-7.0 -7.1 -7.2 -7.3 -7.4
-8.0 -8.1 -8.2 -8.3 -8.4
-9.0 -9.1 -9.2 -9.3 -9.4
对于第一行,我只需要读取一些值,而对于其他(块),则需要逐块读取它们。 到目前为止,我写的是这样的:
import tkinter as tk
from tkinter import filedialog
import numpy as np
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
f = open(file_path)
with open(file_path) as fp:
first_line = fp.readline()
phone_number = first_line[0:28]
second_line = fp.readline()
nums2 = second_line.split(' ')
total_elements = (float(nums2[2]))
first_block = []
first_block_lines = range(5,int(5+(total_elements/5)))
for position,line in enumerate(f):
if position in first_block_lines:
first_block.append(line)
second_block = []
second_block_lines = range(int(5+(total_elements/5)+1),int(5+(total_elements/5)+1+total_elements/5))
for position,line in enumerate(f):
if position in second_block_lines:
second_block.append(line)
在我的真实情况下,我有数百个块,所有块都具有相同数量的行和列。我遍历区块(range(...)
)的方式很糟糕,我想知道如何使其变得更智能。
请让我知道我是否不清楚。非常感谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)