この回答(以下に表示)に概説されているようにコードを設定しました:
from itertools import tee, islice, chain, izip
def previous_and_next(some_iterable):
prevs, items, nexts = tee(some_iterable, 3)
prevs = chain([None], prevs)
nexts = chain(islice(nexts, 1, None), [None])
return izip(prevs, items, nexts)
x = open('out2.txt','r')
lines = x.readlines()
for previous, item, next in previous_and_next(lines):
print "Current: ", item , "Next: ", next, "Previous: ", previous
if item == '0':
print "root"
elif item == '2':
print "doc"
else:
print "none"
x.close()
out2.txt
このように見えます:
0
2
4
6
8
10
このコードは、のようなものを使用する場合は正常に機能しlist = [0,2,4,6,8,10]
ますが、テキストファイルの行をリストに使用する場合は機能しません。テキストファイルの行をリストとして使用するにはどうすればよいですか。これをしていませんx.readlines()
か?最終的には、結果に応じて出力を印刷できる必要がありitem, next, and previous
ます。
現在の出力は次のとおりです。
Current: 0
Next: 2
Previous: None
none
Current: 2
Next: 4
Previous: 0
none
Current: 4
Next: 6
Previous: 2
none
Current: 6
Next: 8
Previous: 4
none
Current: 8
Next: 10 Previous: 6
none
Current: 10 Next: None Previous: 8
none
必要な出力は次のとおりです。
Current: 0
Next: 2
Previous: None
**root**
Current: 2
Next: 4
Previous: 0
**doc**
none
Current: 4
Next: 6
Previous: 2
none
Current: 6
Next: 8
Previous: 4
none
Current: 8
Next: 10 Previous: 6
none
Current: 10 Next: None Previous: 8
none