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

标签 python list python-itertools

我已经按照 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/

相关文章:

python - 从 itertools 组合列表结果中删除括号

python - 在不使用 sklearn 的情况下使用 SGD(LogLoss 随着每个时期的增加而增加)

python - scipy.stats 中 ttest 的两种实现的不同结果

python - ModuleNotFoundError 在从 importlib 导入的模块上使用 "classic"导入

list - 将括号字符串解析为 Haskell 中的嵌套列表

.NET:结合两个通用列表

python - Open AI Gym 观察空间形状问题

python-3.x - 为什么Python在这段看似简单的代码中不拼接换行符呢?

python - Itertools 不可调用

python - 将 "pairs"的列表转换为字典的字典?