Python迭代器中的最后一个元素

问题描述:

我想迭代一个文件的行,并为每个文件输出一些输出。所有打印的行最后应该有一个,\n,除了最后一行。Python迭代器中的最后一个元素

我的第一种方法是使用查找hasNext()方法,该方法不存在。我意识到StopIteration异常会引发,但我不知道如何以Pythonic方式使用它来实现我想要的效果。

+0

是否最后一行您正在阅读的文件是否有换行符? – 2013-03-05 14:59:19

+5

你知道你也可以使用''\ n'.join(lines)'来实现它吗? – gefei 2013-03-05 15:04:33

+0

不要这样做,如果它不适合你的记忆,但。 – 2013-03-05 15:09:55

这里是一个迭代器,给你一个hasNext属性的包装类:

class IteratorEx(object): 
    def __init__(self, it): 
     self.it = iter(it) 
     self.sentinel = object() 
     self.nextItem = next(self.it, self.sentinel) 
     self.hasNext = self.nextItem is not self.sentinel 

    def next(self): 
     ret, self.nextItem = self.nextItem, next(self.it, self.sentinel) 
     self.hasNext = self.nextItem is not self.sentinel 
     return ret 

    def __iter__(self): 
     while self.hasNext: 
      yield self.next() 

演示:

iterex = IteratorEx(xrange(10)) 
for i in iterex: 
    print i, iterex.hasNext 

打印:

0 True 
1 True 
2 True 
3 True 
4 True 
5 True 
6 True 
7 True 
8 True 
9 False 

单独打印第一行,然后预置其他行",\n"

firstline = next(thefile) 
print get_some_output(firstline) 
for line in thefile: 
    print ",\n" + get_some_output(line) 

你可能想先剥离现有的换行符。然后你就可以通过剥离线重复,让你的输出,并使用“\ n”的结果结合在一起,就像这样:

有关你的问题出现在几个下面列出的职位
f = open('YOUR_FILE', 'r') 
print ",\n".join([get_some_output(line.rstrip("\n")) for line in f]) 

答案。虽然其中一些问题与目前的问题有很大不同,但大多数问题都有我在这里列出的信息。请注意,Pavel的答案是比当前问题更清晰的解决方案,但以下几个较旧的答案更一般。

Python: Looping through all but the last item of a list
Have csv.reader tell when it is on the last line
Getting the first and last item in a python for loop
What is the pythonic way to detect the last element in a python 'for' loop?
Python How to I check if last element has been reached in iterator tool chain
Cleanest way to get last item from python iterator
How to treat the last element in list differently in python?
Python: how do i know when i am on the last for cycle
Ignore last \n when using readlines with python
Python Last Iteration in For Loop
Python 3.x: test if generator has elements remaining

一个以上的在右侧边栏的“相关”列表中现在的问题是上市,但其他人没有。 “相关”边栏中的几个问题值得关注,并可能包含在上面的列表中。