我已经按照 this answer 中的概述设置了我的代码(如下所示):
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() 不是这样做的吗?最终,我需要能够根据项目、下一个和上一个
结果打印输出。
当前输出是:
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
最佳答案
文件对象的 readlines()
方法返回文件行的列表,包括换行符。您的检查与不包含换行符的字符串进行比较,因此它们总是失败。
摆脱换行符的一种方法是
lines = (line.strip() for line in open("out2.txt"))
(请注意,您不需要 readlines()
——您可以直接迭代文件对象本身。)
关于Python:使用itertools从文本文件中获取列表中的上一个、当前和下一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8773890/