0

I have a list of object and I want to sort it but there is one caveat.

So lets say the list has an object which has an instance called norm

and norms are like [0.1,0.2,0.3.....0.9]

So if i do something like:

 potential_list.sort(key = lambda x:x._norm, reverse = True)

then it will sort it in somethng like

       [0.9, 0.8... 0.1]

but i want to sort it so wrt to a number so that

     number = 0.3

  then sorted list is [0.4,0.6,0.3,0.7 and so on] because

       0.4-0.3 = 0.1
       abs|0.4-0.5| = 0.1
       0.4 - 0.2 = 0.2
        abs|0.4 - 0.6| = 0.2

  So the sort is because of that difference.

How do i do this. Not that these [0.4,0.6....] are an instance of any object

So its a mix of sorting a list with respect to the closest number in the list python and How to sort a list of objects , based on an attribute of the objects?

Community
  • 1
  • 1
frazman
  • 32,081
  • 75
  • 184
  • 269
  • 2
    I have read this a couple of times and I still don't get quite what you're asking. Could you show an example input and output for your second sort? I can't see where you're getting your values from. – Steve Mayne Apr 23 '12 at 22:12
  • I am a bit confused with how the expected sort list is done. Do you mind to fix the misspell `i want to sort it so wrt to a number so that ` and what is `number = 0.3` doing? I am pretty slow at interpreting other people's problem... are `0.4`, `0.6` an instance of another objects? or are you saying the list is an attribute of the object? – CppLearner Apr 23 '12 at 22:13

2 Answers2

2

Exactly how you described it.

key=lambda x: abs(x._norm - number)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

Well, simply combine them:

>>> class X(object):
...     def __init__(self, n): self._norm = n
...     def __repr__(self): return str(self._norm)
... 
>>> lst = [X(0.1),X(0.2), X(0.3), X(0.4), X(0.5), X(0.6), X(0.7), X(0.8), X(0.9)]
>>> lst.sort(key=lambda x: abs(x._norm - 0.5))
>>> lst
[0.5, 0.4, 0.6, 0.7, 0.3, 0.2, 0.8, 0.1, 0.9]
phihag
  • 278,196
  • 72
  • 453
  • 469