Python:使用itertools从文本文件中获取列表的前一项、当前项和下一项

1 投票
1 回答
1754 浏览
提问于 2025-04-17 09:45

我按照这个回答的步骤设置了我的代码(如下所示):

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, 和 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

1 个回答

3

文件对象的 readlines() 方法会返回文件中所有行的列表,包括换行符。你进行的检查是和不带换行符的字符串进行比较,所以总是会失败。

去掉换行符的一种方法是

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

(注意,你其实不需要使用 readlines(),可以直接遍历文件对象本身。)

撰写回答