Python list Two unequal-length lists cross merge

Source: Internet
Author: User
Tags python list

When you encounter a requirement, you need to cross-merge a list of two lengths that 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 merge A, b into C

c = [1, 2, 3, 4, 6, 8]

See the definition function on the net, or use zip, oneself feel not too ideal, want to daoteng under, of course, the following method may have been thought of.

Method One: Write 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 Two: List expression (super long, tried for a long time to get 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

Python list Two unequal-length lists cross merge

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.