Simple implementation of Python flattening nested lists

Source: Internet
Author: User
List is the most frequently used data type in Python, and there are rich functions available in the standard library.

However, if you convert a multidimensional list into a one-dimensional list (not much of this requirement), it is not easy to find useful functions,

You know, Ruby, Mathematica, and groovy are flatten.

If the list is less dimensional and regular, it's good to do

For example:

Li=[[1,2],[3,4],[5,6]]print [J for I under Li for J in I] #orfrom itertools import chainprint list (Chain (*li)) #ora =[[1,2],[3,4 ],[5,6]]t=[][t.extend (i) for i in A]print t#orprint sum (li,[])

For more complex, such as: li=[1,[2],[[3]],[[4,[5],6]], the above method is not good, we have to change a method,
From the structure of the tree-like, it is easy to associate with the directory traversal, so there is the following approach:

def flat (tree):  res = []  for I in tree:    if isinstance (i, list):      Res.extend (flat (i))    else:      Res.append (i)  return res

Another way of thinking, nested list is nothing more than a lot of pairs of square brackets, one-dimensional list only a pair, the middle of the removal of the line, converted to a string is good to do

def flatten (seq):  s=str (seq). replace (' [', ') '. Replace ('] ', ') #当然也可以用正则  return [eval (x) for x in S.split (', ') If X.strip ()]

However, this practice does not help when a string containing "[" or "]" appears in the list, and needs to be improved.

Other methods:

In a foreign forum, the same is recursive, a line to fix

Flat=lambda l:sum (Map (flat,l), []) if Isinstance (l,list) Else [L]

The following method uses the Tkinter module to see the method in the mailing list. It is estimated that many students do not know that it can do it, also is a python comes with. Note that the Windows version of Python comes with the Tkinter module, and Linux defaults to No

From Tkinter import _flattenli=reduce (lambda *x:list (x), Range (2,6), [1]) print liprint _flatten (li) #Out: #[[[[[1], 2], 3] , 4], 5]# (1, 2, 3, 4, 5) #对元组同样适用

There are also third-party modules that provide such functions as sympy, numpy, pipe, etc.

For nested tuples, you don't need to say more, just a little bit of change.

Above this python flattening nested list of simple implementation is the small part to share the whole content of everyone, hope to give you a reference, but also hope that we support the script home.

  • 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.