Order of pytho objects list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gillest
    New Member
    • Jun 2010
    • 2

    Order of pytho objects list

    • I have a list of objects.
    • Each object has a variable named number.
    • All objects are in a list


    What I would like to achieve in the most efficient manner is to order my objects by their number var.

    An example :

    Object1
    _number=1

    Object4
    _number=2

    Object3
    _number=5

    ListObj=[Object1,Object3 ,Object4]

    What I want to get is to be able to get my objects in order by their number :
    Object1, Object4, Object3
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    It might be possible to do it by assigning the special methods that allow <, > and = to be used, and then sorting it. I haven't tried this.

    But failing this, what you want to do is use the bisect module (wonderfully efficient):

    Code:
    import bisect
    
    class whatever:
        def __init__(self,num):
            self.num=num
        def __repr__(self):
            return "whatever %d"%self.num
        
    ob1=whatever(5)
    ob2=whatever(3)
    ob3=whatever(4)
    
    list1=[ob1,ob2,ob3]
    
    def mysort(myl):
        ans=[]
        order=[]
        for ob in myl:
            i=bisect.bisect_left(order,ob.num)
            order.insert(i,ob.num)
            ans.insert(i,ob)
        return ans
    
    print "original:",list1
    list2=mysort(list1)
    print "sorted:",list2
    This prints out
    Code:
    original: [whatever 5, whatever 3, whatever 4]
    sorted: [whatever 3, whatever 4, whatever 5]

    Comment

    • gillest
      New Member
      • Jun 2010
      • 2

      #3
      Thanks

      It would have take a long time to figure it out myself.
      Thanks a lot.

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Here's an example of sorting on a key in Python 2.4 and higher:
        Code:
        >>> class Obj(object):
        ... 	def __init__(self, num):
        ... 		self.num = num
        ... 		
        >>> objects = [Obj(6), Obj(2), Obj(12), Obj(4)]
        >>> objects
        [<__main__.Obj object at 0x034C7510>, <__main__.Obj object at 0x034C7410>, <__main__.Obj object at 0x034C7350>, <__main__.Obj object at 0x034C7310>]
        >>> [item.num for item in objects]
        [6, 2, 12, 4]
        >>> objects.sort(key=lambda x: x.num)
        >>> objects
        [<__main__.Obj object at 0x034C7410>, <__main__.Obj object at 0x034C7310>, <__main__.Obj object at 0x034C7510>, <__main__.Obj object at 0x034C7350>]
        >>> [item.num for item in objects]
        [2, 4, 6, 12]
        >>>

        Comment

        Working...