[Python] tips for solving python chained extend

Source: Internet
Author: User
Tags python list

The list in Python is known to be extend, and is designed to combine two lists into one. For example [1,2,3].extend ([4,5,6]) =[1,2,3,4,5,6]

If there is a list of list, I want to reduce them into a list, how to do? People who know a bit of functional programming will think of reduce, but direct reduce (lambda x,y:x.extend (y), lists) is not possible because the original implementation in the Python list class does not allow chained extend.

My workaround is to inherit the list class to add chained extend operations.

1 class listwithlinkextend (list): 2   def Extend (self, value): 3     Super (Listwithlinkextend, self). Extend (value)4     return Self

This makes it easy to reduce the list of lists by chaining extend.

1 x = [[], [4,5,6], [7,8,9]]2 list (reduce (lambda A, B: Listwithlinkextend (a). Extend (Listwithlinkextend (b)), X))

[Python] tips for solving python chained extend

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.