PYTHON flattened nesting list and python flattened nesting

Source: Internet
Author: User

PYTHON flattened nesting list and python flattened nesting

List is the most frequently used data type in Python. A wide range of functions are available in the standard library.
However, if you convert a multi-dimensional list to a one-dimensional list (you don't know how many such requirements are required), it's really hard to find useful functions,
You must know that Ruby, Mathematica, and Groovy are flatten.
If the list has few dimensions and rules, it is easy to do.
For example:

li=[[1,2],[3,4],[5,6]]print [j for i in 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 complex scenarios, such as: li = [1, [2], [[3], [4, [5], 6], the above method won't work well. You have to change the method,
In terms of structure, it looks like a tree, and it is easy to think of directory traversal, so we have the following practices:

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

Another idea is that the nested list is nothing more than square brackets with many pairs. The one-dimensional list has only one pair. just remove the middle and convert it to a string.

Def flatten (seq): s = str (seq ). replace ('[',''). replace (']', '') # You can also use the regular return [eval (x) for x in s. split (',') if x. strip ()]

However, this method does not work for strings containing "[" or "]" in the list and needs to be improved.


Other methods:

What I saw on a foreign Forum is also recursion, and one line is done.

flat=lambda L: sum(map(flat,L),[]) if isinstance(L,list) else [L]

The following method uses the Tkinter module, which is displayed in the mail list. It is estimated that many of you still don't know what it can do. It is also python's own. Note: python for windows comes with Tkinter modules, but not for linux by default.

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) # applies to tuples

 

Some third-party modules provide such functions, such as sympy, numpy, and pipe.

For nested tuples, you don't need to talk about it. You just need to change it a little.

FROM: http://www.cnblogs.com/c-hy/archive/2012/09/21/2696703.html

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.