我已按照此答案中的概述设置了我的代码(如下所示):
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