Praful Bagai
Praful Bagai

Reputation: 17392

Ordering a list according to hierarchy

I've a list

a = ["Asia/Pacific", "North America", "India,Asia/Pacific", "China, Asia/Pacific", "New Delhi, India, Asia/Pacific", "Bangalore, India,Asia/Pacific",  "Shangai, China, Asia/Pacific", "US, North America", "New York, US, North America"]

I want it to be sorted in such as way that all the leaf and parent node comes together. For eg:-

a = ["Asia/Pacific", "India,Asia/Pacific", "New Delhi, India, Asia/Pacific", "Bangalore, India,Asia/Pacific",  "China, Asia/Pacific", "Shangai, China, Asia/Pacific", "North America", "US, North America", "New York, US, North America"]

To make it more clear, it should follow a tree structure like -

Asia/Pacific
   India
       Bangalore
            Sarjapur Road
            MG Road
       Mumbai
             Santa Cruz
   China
       Beijing
       Shanghai

North America
   USA
   Canada
   Mexico

How can I go about?

Upvotes: 0

Views: 64

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123420

Build a key that reflects the structure; split on comma and reverse:

sorted(a, key=lambda p: map(str.strip, p.split(',')[::-1]))

This sorts the last component alphabetically, then for the same region, sorts the country alphabetically, etc. The str.strip mapping is needed to remove the extra spaces.

Demo:

>>> a = ["Asia/Pacific", "North America", "India,Asia/Pacific", "China, Asia/Pacific", "New Delhi, India, Asia/Pacific", "Bangalore, India,Asia/Pacific",  "Shangai, China, Asia/Pacific", "US, North America", "New York, US, North America"]
>>> sorted(a, key=lambda p: map(str.strip, p.split(',')[::-1]))
['Asia/Pacific', 'China, Asia/Pacific', 'Shangai, China, Asia/Pacific', 'India,Asia/Pacific', 'Bangalore, India,Asia/Pacific', 'New Delhi, India, Asia/Pacific', 'North America', 'US, North America', 'New York, US, North America']

Upvotes: 2

Related Questions