1

我已按照此答案中的概述设置了我的代码(如下所示):

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
4

1 回答 1

3

readlines()文件对象的方法返回包含换行符的文件行列表。您的检查与不包括换行符的字符串进行比较,因此它们总是失败。

摆脱换行符的一种方法是

lines = (line.strip() for line in open("out2.txt"))

(请注意,您不需要readlines()- 您可以直接迭代文件对象本身。)

于 2012-01-07T23:21:47.447 回答