two files into an alternate list

Tim Chase python.list at tim.thechases.com
Mon Oct 29 21:39:13 EDT 2007


>     i have a file :
>          file 1:
> 1
> 2
> 3
> 4
> 5
> 6
> 
> file2:
> a
> b
> c
> d
> e
> f
> how do i make the two files into  list like this =
> [1,a,2,b,3,c,4,d,5,e,6,f]

  from itertools import cycle
  def serialize(*sources):
    while True:
      for source in sources:
        yield source.next()
  def stripper(iterator):
    for thing in iterator:
      yield thing.strip()
  for thing in serialize(
      stripper(file('file1.txt')),
      stripper(file('file2.txt'))
      ):
    print thing

As a previous responder noted, there are a number of ways to
treat the edge cases when the lengths of the files don't match.
Since you left the condition underqualified, I chose to let it
expire when the first one gave out rather than try and deal with
the complications of such ambiguity.

-tkc






More information about the Python-list mailing list