two files into an alternate list

Ricardo Aráoz ricaraoz at gmail.com
Wed Oct 31 15:28:39 CET 2007


Tim Chase wrote:
>>     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
> 

Or maybe just :

>>> r = []
>>> for a, b in map(None
		, (int(i.strip('\n')) for i in open('file1.txt'))
		, (i.strip('\n') for i in open('file2.txt'))) :
	r.append(a)
	r.append(b)

>>> r
[1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e', None, 'f']






More information about the Python-list mailing list