When encountering a requirement, it is necessary to cross-merge two lists whose lengths are not necessarily equal. Like a zipper (the zippers on both sides are not necessarily equal).
Such as:
a = [1, 3, 5]
b = [2, 4, 6, 8]
Need to combine a, b into c
c = [1, 2, 3, 4, 6, 8]
I saw the definition function on the Internet again, or used zip. I felt that it was not ideal, so I wanted to go down. Of course, it is possible that the following methods have already been thought of.
Method 1: Write a for loop
a = [1, 3, 5]
b = [2, 4, 6, 8]
c = [ ]
for i in range( max ( len( a ), len( b ) ) ):
if a:
c.append( a.pop() )
if b:
c.append( b.pop() )
Method 2: List expression (super long, it took a long time to figure it out)
a = [1, 3, 5]
b = [2, 4, 6, 8]
a.reverse()
b.reverse()
c = [ ( lambda i: a.pop() if ( a! = [ ] and ( i % 2 ==0 or b==[ ] )) else b.pop() )( i ) for i in range( len( a ) + len( b ) )]
-- by Clay