Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

python - reading lines 2 at a time

Is there a better way to read lines two at a time from a file in python than:

with open(fn) as f:
    for line in f:
        try:
            line2 = f.next()
        except StopIteration:
            line2 = ''
        print line, line2 # or something more interesting

I'm in 2.5.4. Anything different in newer versions?

EDIT: a deleted answer noted: in py3k you'd need to do next(f) instead of f.next(). Not to mention the print change

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import itertools

with open(fn) as f:
  for line, line2 in itertools.izip_longest(f, f, fillvalue=''):
    print line, line2

Alas, izip_longest requires Python 2.6 or better; 2.5 only has izip, which would truncate the last line if f has an odd number of lines. It's quite easy to supply the equivalent functionality as a generator, of course.

Here's a more general "N at a time" iterator-wrapper:

def natatime(itr, fillvalue=None, n=2):
  return itertools.izip_longest(*(iter(itr),)*n, fillvalue=fillvalue)

itertools is generally the best way to go, but, if you insisted on implementing it by yourself, then:

def natatime_no_itertools(itr, fillvalue=None, n=2):
  x = iter(itr)
  for item in x:
    yield (item,) + tuple(next(x, fillvalue) for _ in xrange(n-1))

In 2.5, I think the best approach is actually not a generator, but another itertools-based solution:

def natatime_25(itr, fillvalue=None, n=2):
  x = itertools.chain(iter(itr), (fillvalue,) * (n-1))
  return itertools.izip(*(x,)*n)

(since 2.5 doesn't have the built-in next, as well as missing izip_longest).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...