python - Group list-items by order of appearance in unsorted list -


test cases:

group_ordered([1,3,2,3,6,3,1]) = [1,1,3,3,3,2,6] group_ordered([1,2,3,4,5,6,1]) = [1,1,2,3,4,5,6] 

i have code already, it's ugly , slow on large lists well, since each unique item i'm looking @ whole list. came algorithm, wondering if there faster, cleaner, or more pythonic way can this:

def make_order_list(list_in):     order_list = []     item in list_in:         if item not in order_list:             order_list.append(item)     return order_list   def group_ordered(list_in):     if list_in none:         return none     order_list = make_order_list(list_in)     current = 0     item in order_list:         search = current + 1         while true:             try:                 if list_in[search] != item:                     search += 1                 else:                     current += 1                     list_in[current], list_in[search] = list_in[search], list_in[current]                     search += 1             except indexerror:                 break     return list_in 

use collections.ordereddict() instance grouping:

from collections import ordereddict  def group_ordered(list_in):     result = ordereddict()     value in list_in:         result.setdefault(value, []).append(value)     return [v group in result.values() v in group] 

because specialised dictionary object tracks insertion order of key, output ordered first occurrence of group value.

demo:

>>> group_ordered([1,3,2,3,6,3,1]) [1, 1, 3, 3, 3, 2, 6] >>> group_ordered([1,2,3,4,5,6,1]) [1, 1, 2, 3, 4, 5, 6] 

Comments