【问题标题】:Sort the list L by the ratio of the elements in the 2-tuples in place [duplicate]按 2 元组中元素的比率对列表 L 进行排序 [重复]
【发布时间】:2017-06-30 18:53:41
【问题描述】:

我正在尝试按 2 元组中元素的比率对列表 L 进行排序。

Parameters
----------
L : {list} of 2-tuples ({tuple}) of {int}

Returns
-------
None   

Example
-------
>>> L = [(2, 4), (8, 5), (1, 3), (9, 4), (3, 5)]
>>> sort_by_ratio(L)
>>> L
[(1, 3), (2, 4), (3, 5), (8, 5), (9, 4)]

到现在为止

L[:] = sorted(L,key = lambda ratio: ratio[0]/ratio[1])

但它以某种方式给了我[(2, 4),(1, 3),(3, 5), (8, 5), (9, 4)]的列表

我哪里做错了?

【问题讨论】:

  • / for ints 是 Python 2 上的地板除法。

标签: python python-2.7 list sorting


【解决方案1】:
L = [(2, 4), (8, 5), (1, 3), (9, 4), (3, 5)]
L[:] = sorted(L,key = lambda ratio: 1.*ratio[0]/ratio[1])
print L

【讨论】:

  • float(ratio[0])/ratio[1]。或者更好:from __future__ import division.
猜你喜欢
  • 2012-03-13
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 2020-10-19
  • 2017-09-08
相关资源
最近更新 更多