I have setup my code as outlined in this answer (shown below):
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
looks like this:
0
2
4
6
8
10
This code works fine when using something like list = [0,2,4,6,8,10]
but not when using the lines of a text file into a list. How can I use the lines of a text file as a list. Isn't x.readlines()
doing this? Ultimately I need to be able to print output depending on the item, next, and previous
results.
Current output is:
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
Desired output should be:
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