我發佈了一個關於How to interate over N lines of a text file in Python的問題,但我想讓該程序更適用於N行(例如,而不是必須一次收集兩行採取四個或六個線路在同一時間在循環中遍歷N行,然後轉到下一個循環
我希望把這個disp.txt:
116 C 0.12 -0.91 0.39 -0.40 0.31 0.85 -0.66 -0.18 -0.22
117 O 0.00 -0.02 0.00 -0.05 0.05 0.12 -0.57 -0.26 -0.29
116 C -0.03 -0.04 0.00 0.01 0.09 0.19 -0.71 -0.21 -0.26
117 O -0.14 0.88 -0.45 0.47 -0.33 -0.79 0.57 0.16 0.19
要這樣:
vibration 1
0.12 -0.91 0.39
0.0 -0.02 0.0
vibration 2
-0.4 0.31 0.85
-0.05 0.05 0.12
vibration 3
-0.66 -0.18 -0.22
-0.57 -0.26 -0.29
vibration 4
-0.03 -0.04 0.00
-0.14 0.88 -0.45
vibration 5 ...
下面是我到目前爲止
vibration = 1
with open('disp1.txt','r') as f, open('disp2.txt', 'w') as out:
while True:
next_lines = list(islice(f,2))
m = next_lines
for i in m:
s = i.strip().split('\n')
for j in s:
p = j.split()
v = len(p)
for u in range(2,5,3):
out.write('vibration {}\n'.format(vibration))
out.write(' '.join(p[u:u+3])+'\n')
vibration += 1
for x in range(5,8,3):
out.write(' '.join(p[x:x+3])+'\n')
for y in range(8,11,3):
out.write(' '.join(p[y:y+3])+'\n')
if not next_lines:
break
該圖是這樣的:
vibration 1
0.12 -0.91 0.39
-0.40 0.31 0.85
-0.66 -0.18 -0.22
vibration 2
0.00 -0.02 0.00
-0.05 0.05 0.12
-0.57 -0.26 -0.29
vibration 3
-0.03 -0.04 0.00
0.01 0.09 0.19
-0.71 -0.21 -0.26
vibration 4
-0.14 0.88 -0.45
0.47 -0.33 -0.79
0.57 0.16 0.19
所以它的閱讀在整個頁面,而不是閱讀數前三列的前兩行,然後繼續下一組的三個等等。 通過使用isplice它一次讀兩行,但由於我不明白這兩個行都不通過第一個循環(對於範圍(2,5,3):)中的u(在範圍內(2,5,3):),對於範圍內的x(5,8,3):) 取而代之的是將每條線貫穿每個循環。 任何人都可以幫助我嗎?
謝謝。
但0.12 -0.91 0.39 -0.40 0.31 0.85 -0.66 - 0.18 -0.22是一行! –
另外,請使用下面的代碼:http://www.pythontutor.com/visualize.html#mode=edit –
我的答案是否有效?如果是這樣,請將其標爲正確(綠色檢查)。 –