私はこのような巨大な一定形式のテキストファイルを持っています:
first line
2nd line
3rd line
#Mi Mj
#Ni Nj Nk
#Pi Pj
#----------- The numeric values start here ------
M0 M1
N0 N1 N2
P0 P1
M1 M2
N1 N2 N3
P1 P2
M2 M3
N2 N2 N3
P2 P3
...
1行目から7行目をスキップし、1行目、2行目、3行目ごとに7行目以降のファイルを読み取り、3つの異なるリストに保存する必要があります。
他の2行をスキップすることで、コードの1行ごとにそれを実行できましたが、2行目と3行ごとに実行することはできませんでした。ただし、next(fileobject)を2回使用することは、効率的な方法ではありません。それで、誰かが私にそれを巨大なファイルのためにどのように最善にすることができるか教えてもらえますか?私は最後にそのような結果が必要です:
list1 = [M0, M1, M1, M2, M2, M3]
list2= [N0,N1,N2,N1, N2,N3,N2,N2, N3]
list3= [P0, P1, P1, P2,P2, P3]
これが私のコードです:
# Python 3
myfile = open('myfile.txt', 'r')
m,n,p = [], [], []
for line in myfile:
ll = line.strip() # string
if not ll.startswith("#"):
row = ll.split() # list
print(row)
try:
m.append(row[0]) # append first column of every third line
except IndexError:
print('There is not a standard line: ', line)
next(myfile)
next(myfile)
print(m)
myfile.close()
ファイルを3行のグループに分割する必要があります。
# based on 'grouper()' example from the python 2 itertools documentation
from itertools import izip
def partition(lines, n):
iters = [iter(lines)] * n
return izip(*iters)
したがって、実行list(partition("ABCDEFGHI", 3))
すると次のようになります。
["ABC", "DEF", "GHI"]
次に、結果を分解して再圧縮します。
partitions = partition("ABCDEFGHI", 3)
splits = zip(*partitions)
したがって、コードは次のようになります。
from itertools import izip, islice
def partition(lines, n):
iters = [iter(lines)] * n
return izip(*iters)
with open("myfile.txt") as f:
keep = islice(f, 7, None) # drop the first 7 lines
parts = partition(keep, 3) # partition into groups of 3
groups = izip(*parts) # group the lines by their index % 3
M, N, P = [sum((g.split() for g in group), []) for group in groups]
簡単にするために、エラーのチェック/処理は省略しました。
参照:https://docs.python.org/2/library/itertools.html?highlight = itertools#recipes
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加