zip list with different length

G

ginstrom

elements, say len(a) = 5, len(b) = 3 ....
I want the results to be
[(0, 0), (1, 1), (2, 2) , (3) , (4) ]
can it be done?

A bit cumbersome, but at least shows it's possible:
common = min( len(a), len(b) )
results = zip( a[:common], b[:common] )
if len( a ) < len( b ):
a = b
return results + [ (x,) for x in a[common:] ]
superZip( range( 5 ), range( 3 ) ) [(0, 0), (1, 1), (2, 2), (3,), (4,)]
superZip( range( 3 ), range( 5 ) ) [(0, 0), (1, 1), (2, 2), (3,), (4,)]
superZip( range( 0 ), range( 5 ) ) [(0,), (1,), (2,), (3,), (4,)]
superZip( range( 3 ), range( 3 ) )
[(0, 0), (1, 1), (2, 2)]

Regards,
Ryan Ginstrom
 
M

MC

Hi!

Brutal, not exact answer, but:

a = range(5)
b = range(3)
print zip(a+[None]*(len(b)-len(a)),b+[None]*(len(a)-len(b)))
 
P

Peter Otten

suppose i have 2 lists, a, b then have different number of elements,
say len(a) = 5, len(b) = 3
a = range(5)
b = range(3)
zip(b,a) [(0, 0), (1, 1), (2, 2)]
zip(a,b)
[(0, 0), (1, 1), (2, 2)]

I want the results to be
[(0, 0), (1, 1), (2, 2) , (3) , (4) ]
can it be done?
thanks

from itertools import izip, chain, repeat, takewhile, starmap

def zip_longest(*seqs):
padded = [chain(izip(s), repeat(())) for s in seqs]
return takewhile(bool, starmap(sum, izip(izip(*padded), repeat(()))))

Just to bring itertools to your attention :)

Peter
 
A

Alexander Schmolck

(e-mail address removed) writes:

C> hi
suppose i have 2 lists, a, b then have different number of elements,
say len(a) = 5, len(b) = 3
a = range(5)
b = range(3)
zip(b,a) [(0, 0), (1, 1), (2, 2)]
zip(a,b)
[(0, 0), (1, 1), (2, 2)]

I want the results to be
[(0, 0), (1, 1), (2, 2) , (3) , (4) ]
can it be done?

map(lambda *t: filter(lambda x: x is not None,t),a,b)

'as
 
A

Alexander Schmolck

MC said:
Hi!

Brutal, not exact answer, but:

a = range(5)
b = range(3)
print zip(a+[None]*(len(b)-len(a)),b+[None]*(len(a)-len(b)))

You reinvented map(None,a,b).

'as
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top