Python - How to sort multidimensional list to two-dimensional list?

python sort multidimensional list
python sort 2d list by two columns
python sort nested list by second element
python sort 2d array by column descending
python sorted
python sort list of lists
2d list python
merge sort 2d array python

How i can sort multidimensional list to two-dimensional list?

Multidimensional input: [8, [6, 7, [-1], [4, [[10]]], 2], 1]

Desired two-dimensional output: [[8, 1], [6, 7, 2], [-1, 4], [], [10]]

all same depth list items need to be in same list.

The idea is basically the same that the one in @TerryA answer, but using setdefault and checking at the end of the for loop if something of the depth was added:

lst = [8, [6, 7, [-1], [4, [[10]]], 2], 1]


def depths(l):
    def flatten(l, start=0, depth={}):

        for e in l:
            if isinstance(e, list):
                flatten(e, start=start + 1, depth=depth)
            else:
                depth.setdefault(start, []).append(e)
         if start not in depth:
            depth[start] = []

    d = {}
    flatten(l, depth=d)

    return [d[i] for i in range(max(d) + 1)]


result = depths(lst)
print(result)

Output

[[8, 1], [6, 7, 2], [-1, 4], [], [10]]

Two-dimensional lists (arrays) - Learn Python 3, How to sort 2d list by the second or third sub item in a lists. Great for making high score tables.Duration: 4:05 Posted: Jan 16, 2017 Sorting 2D list python [closed] Ask Question Asked 6 years, 9 months ago. To sort a list of lists on the second column, use operator.itemgetter()

You could perhaps use a defaultdict here to measure the depth of each element, along with recursion:

from collections import defaultdict
L = [8, [6, 7, [-1], [4, [[10]]], 2], 1]
res = defaultdict(list)
def myfunc(L, depth):
    for i in L:
        if isinstance(i, list):
            myfunc(i, depth+1)
        else:
            res[depth].append(i)

myfunc(L, 0)

The defaultdict will then look like this:

defaultdict(<class 'list'>, {0: [8, 1], 1: [6, 7, 2], 2: [-1, 4], 4: [10]})

You'll then need to translate the defaultdict back to what you want. Note that the default dict will not contain an empty list because it can't detect it (ie: [[10]] and [10] are both lists), but what it will have is a gap in the range (notice how the depth 3 is missing in the defaultdict).

final = []
for i in range(max(res)+1):
    if i not in res:
        final.append([])
    else:
        final.append(res[i])

print(final)

Very messy, I'm sure improvements could be made.

Python: list of lists, Here's a quick and elegant way to sort complex objects in Python (for instance, a list of lists or a 2D array), using the objects' indices as the key. Sort the multi-dimensional array in descending order on the basis of 2nd column: list_name.sort(key=lambda x:x[1],reverse=True)

My option with recursion and without any dependencies:

lst = [8, [6, 7, [-1], [4, [[10]]], 2], 1]

def flat_group(lst, deep = 0, res = None):
  if res == None: res = []
  for item in lst:
    if len(res) <= deep: res.append([])
    if not type(item) == list:
      res[deep].append((item))
    else:
      flat_group(item, deep + 1, res)
  return res


print(flat_group(lst))
#=> [[8, 1], [6, 7, 2], [-1, 4], [], [10]]


To show How it works, I split the method in two:

def flat(lst, deep = 0, res = []):
  for item in lst:
    if not type(item) == list:
      res.append((deep, item))
    else:
      flat(item, deep + 1, res)
  return res

def group(lst):
  flatten = flat(lst)
  max_n = max(flatten)[0]
  res = [[] for _ in range(0,max_n+1)]
  for deep, item in flatten:
    res[deep].append(item)
  return res

print(group(lst))
#=> [[8, 1], [6, 7, 2], [-1, 4], [], [10]]

flat(lst) is a recursive method that builds a flat list of tuples where each tuple contains the value and the deep inside the original list. So the call flat(lst) returns:

# [(0, 8), (1, 6), (1, 7), (2, -1), (2, 4), (4, 10), (1, 2), (0, 1)]

Then group(lst) builds a list of n+1 empty sub-list, where n is the maximum depth, it iterates over the result of flat(lst) and append each element by index to the proper sub-list.

The flat_group(lst) does almost the same.

Sorting two dimensional lists in Python, 5.16 Two-Dimensional Lists. Lists can contain other lists as elements. A typical use of such nested (or multidimensional) lists is to represent  There can be more than one additional dimension to lists in Python. Keeping in mind that a list can hold other lists, that basic principle can be applied over and over. Multi-dimensional lists are the lists within lists. Usually, a dictionary will be the better choice rather than a multi-dimensional list in Python.

You can do this by first generating a dictionary of elements at each depth (with depth as key in this dictionary and list of elements of that depth as value). The recursive function get_elements_by_depth below does this. Then all you need to do is flatten the values of that dictionary. (the function flatten_by_depth below does what you need).

from collections import defaultdict

def get_elements_by_depth(ls, cur_depth, cur_dict):
    """
        returns a dictionary with depth as key and a list of all
        elements that have that depth as value
    """
    for x in ls:
        if isinstance(x, list):
            get_elements_by_depth(x, cur_depth + 1, cur_dict)
        else:
            cur_dict[cur_depth].append(x)
    return cur_dict


def flatten_by_depth(ls):
    """
        returns a list of lists, where the list at index i 
        contains all elements of depth i
    """
    elements_by_depth = get_elements_by_depth(ls, 0, defaultdict(list))
    max_depth = max(elements_by_depth.keys())
    # Since we're using a defaultdict, we don't have to worry about
    # missing keys in elements_by_depth
    return [
        elements_by_depth[i]
        for i in xrange(max_depth + 1)
    ]

> flatten_by_depth([8, [6, 7, [-1], [4, [[10]]], 2], 1])
[[8, 1], [6, 7, 2], [-1, 4], [], [10]]

sorting multidimensional lists, This tutorial is for Processing's Python Mode. A two-dimensional list is really nothing more than an list of lists (a three-dimensional list is a list of For a two-​dimensional list, in order to reference every element, we must use two nested loops. The syntax of the sort () method is: list.sort (key=, reverse=) Alternatively, you can also use Python's built-in sorted () function for the same purpose. sorted (list, key=, reverse=)

The recursive approach taken by the other answers comes with the recursion limit imposed by Python and the overhead of two passes. A more efficient one-pass iterative approach is to implement breadth-first search using a queue of tuples of lists and associated depths:

from collections import deque
def flatten(lst):
    output = []
    q = deque([(lst, 0)])
    while q:
        l, depth = q.popleft()
        for i in l:
            if isinstance(i, list):
                q.append((i, depth + 1))
            else:
                while depth >= len(output):
                    output.append([])
                output[-1].append(i)
    return output

so that:

flatten([8, [6, 7, [-1], [4, [[10]]], 2], 1])

returns:

[[8, 1], [6, 7, 2], [-1, 4], [], [10]]

5.16 Two-Dimensional Lists, Here we have used the technique of Bubble Sort to perform the sorting. We have tried to access the second element of the sublists using the nested loops. (A list of eight numbers can be seen in the image) Although it's not too common, you may sometimes encounter multidimensional lists. Especially, when it comes to game applications. Two-dimensional list. A good representation of a 2-dimensional list is a grid because technically, it is one.

Two-Dimensional Lists \ Tutorials, All are means of accomplishing a similar task: sorting the values in a list or array. sort along specific rows or columns of a multidimensional array using the axis We'll start by creating a random set of 10 points on a two-dimensional plane. Sorting HOW TO¶ Author. Andrew Dalke and Raymond Hettinger. Release. 0.1. Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable. In this document, we explore the various techniques for sorting data using Python.

Python, This tutorial goes over 2d lists and multidimensional arrays in general. Are you looking for a quick reference on multidimensional lists in Python instead of a We'll nest the loops in order so that the outer loop iterates over the rows and the  Python | Sort a list according to the second element in sublist In this article, we will learn how to sort any list, according to the second element of the sublist present within the main list. We will see two methods of doing this.

Sorting Arrays, Create a list of lists, or a 2D list. Append empty lists to a list and add elements. Lists are used to hold data, but they are also used to categorize it. Values inside a list can be further broken down into other sets. That's essentially what a multidimensional list is. Two Dimensional Lists What is a list that holds lists? That's all a two dimensional list is. The list below consists of three lists.

Comments
  • what's the logic behind this?
  • Please try to solve the problem by yourself first.
  • @Sociopath he is reorganizing the list by layer depth
  • compute the "depth" of each element, then rebuild a list of lists
  • Can you please tell me whether [[8, 1], [6, 7, 2], [4], [], [10], [-1]] is an acceptable result, and if not, then why?
  • i in res is better than if res.get(i) is None
  • @Jean-FrançoisFabre yup, ty
  • This breaks if there are multiple levels of a sublist without an item, such as [8, [6, 7, [-1], [4, [[[10]]]], 2], 1]. Also, using a mutable object as a default parameter value would result in incorrect results if the function is called more than once.
  • @blhsing, thanks for the advice!! I suppose I fixed the first part, but I'm not able to find a workaround for the object mutation... (with Ruby there is not this issue). Can you address me?
  • Yes you did fix it. +1