データがdata.txt
に含まれているとします。次のコードは、データの必要な部分を正しい順序で印刷します。ファイルの全てのコンテンツが処理された(ただし、すべての値がまだ印刷される場合、これは例外で終了すること
data.txt
x y z
1 1 10
1 2 12
2 1 14
2 2 16
def extract(filepath):
f = open(filepath)
f.readline() # to read out the first line that says "x y z"
while 1:
x = f.readline().strip().split()[-1]
y = f.readline().strip().split()[-1]
print x, y
注data.txt
が連続線でx
とy
座標を有すると仮定すると
)。これを避けるため、data.txt
は、そのような構造されていない場合は、その後、あなたは各行の最初の2つの数字を活用するために必要with open(filepath) as f:
でf = open(filepath)
を交換するには:
data.txt
x y z
1 1 10
2 1 14
1 2 12
2 2 16
from collections import defaultdict
def extract(filepath):
coords = defaultdict(dict)
f = open(filepath)
f.readline() # to read out the first line that says "x y z"
for line in f:
id, axis, val = map(int, line.strip().split())
coords[id][axis] = val
for i in sorted(coords):
print coords[i][1], coords[i][2]
が、これは
を役に立てば幸い最初の2つの列に連続した整数が含まれていないか、整数が全く含まれていない場合はどうなりますか? – balu
答えを見つけた:https://stackoverflow.com/a/15120881/36253 – balu