Python排序列表

时间:2017-01-02 01:24:40

标签: python list

我想从whole[i][0] / whole[i][1]

的最低值到最高值对此列表进行排序
before -> whole = [[60, 20], [100, 50], [120, 30]]

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

2 个答案:

答案 0 :(得分:1)

您可以将list.sort() lambda表达式一起使用:

>>> 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

执行whole.sort()列表的最终值将为:

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

答案 1 :(得分:0)

您可以使用lambda:

进行排序
sorted_list = sorted(whole, lambda x: x[0]/float(x[1]))