frazman
frazman

Reputation: 33273

How to sort data based on heirarchy

I have A list of strings as follows:

["a","aa", "b","bbb", "c", "a::b", "a::b::c", "a::b::d", "b:c"]

I want to sort this as

["a", "a::b", "a::b::c", "a:b::d", "aa", "b", "b:c", "bbb", "c"]

and so on. Just for context.. the "::" acts as a delimiter which represents hierarchy. So, given a top-level object "a".. we first get "a::b", "a::b::c".. and all the children.. before going to next top-level object "aa".

What would be a good way to solve this in python (wondering if there is anything in collections or itertools library, I haven't been able to find appropriate method)?

Upvotes: 0

Views: 55

Answers (3)

Taohidul Islam
Taohidul Islam

Reputation: 5414

my_list = ["a","aa", "b","bbb", "c", "a::b", "a::b::c", "a::b::d", "b:c"]
my_result = sorted(my_list, key=lambda value: value.split('::'))

During sorting every list item will split, like: "a::b::c" will produce a list ["a","b","c"]. Your actual sorting will be among ["a"],["aa"],["b"],["bbb"],["c"],["a","b"],["a","b","c"],["b","c]. And sorting these lists the sort function returns your expected result.

Upvotes: 0

jpp
jpp

Reputation: 164773

Here's one way using just sorted and a custom key:

res = sorted(lst, key=lambda x: x.split('::'))

['a', 'a::b', 'a::b::c', 'a::b::d', 'aa', 'b', 'b:c', 'bbb', 'c']

Upvotes: 7

NPE
NPE

Reputation: 500673

One way is to split each item at ::, then sort, then join:

In [14]: l = ["a", "aa", "b", "bbb", "c", "a::b", "a::b::c", "a::b::d", "b::c"]

In [15]: map('::'.join, sorted(item.split('::') for item in l))
Out[15]: ['a', 'a::b', 'a::b::c', 'a::b::d', 'aa', 'b', 'b::c', 'bbb', 'c']

Upvotes: 3

Related Questions