-5

I want to sort this list from lowest to highest value of whole[i][0] / whole[i][1]

before -> whole = [[60, 20], [100, 50], [120, 30]]

after  -> whole = [[100,50],[60,20],[120,30]]
Mike JS Choi
  • 1,081
  • 9
  • 19

2 Answers2

1

You may use list.sort() along with lambda expression as:

>>> whole = [[60, 20], [100, 50], [120, 30]]

>>> whole.sort(key=lambda x: x[0]/float(x[1]))
#  get the resultant from div as a `float` ^  in Python 2
#  However you may skip the `float` type-cast in Python 3

Final value hold by whole list after doing .sort() will be:

>>> whole
[[100, 50], [60, 20], [120, 30]]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

You can use sorted with a lambda:

sorted_list = sorted(whole, lambda x: x[0]/float(x[1]))
RoHS4U
  • 178
  • 1
  • 7
  • `list.sort` works in-place, your `sorted_list` will be `None`. Better to use `sorted` if you want to create a new sorted list. – MSeifert Jan 02 '17 at 01:33
  • Why did you apply the float to x[1] and not x[0]? – Nebeyu Daniel Jan 02 '17 at 01:59
  • In python 2.x if you divide two ints you will always get an int back regardless of whether or not there is a remainder. If at least one of them is a float you get a float back. Here is another [question](http://stackoverflow.com/a/21317017/6237583) that addresses this. – RoHS4U Jan 02 '17 at 02:11
  • default division in python 2.x is integer so 4/5 will result in 0. so he converted the denominator to float another option is to import division library from fututre i.e. `from __future__ import division` . if you are using python 3 it is not a problem as default division is float.https://www.python.org/dev/peps/pep-0238/ – Yonas Kassa Jan 02 '17 at 02:23