Py学习  »  Python

python中嵌套列表的排序

kakasi_copy_ninja • 3 年前 • 1357 次点击  

我正在做学校分配给我的一道题。 以下是迄今为止的代码:

profits = [1,2,5,6]
weights = [2,3,4,5]
n = 8
ratio = []
count = 0
for i in range(len(profits)):
    ratio.append([])
for i in range(len(ratio)):
    ratio[i].append(weights[i])
    ratio[i].append(profits[i] / weights[i])

产量(比率):

[[2, 0.5], [3, 0.6666666666666666], [4, 1.25], [5, 1.2]]

但问题是,我希望列表按最大比例排序 这样地:

[[4, 1.25], [5, 1.2], [3, 0.6666666666666666], [2, 0.5]]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131653
 
1357 次点击  
文章 [ 2 ]  |  最新文章 3 年前
tshiono
Reply   •   1 楼
tshiono    3 年前

请尝试:

print(sorted(ratio, key=lambda x: float(x[1]), reverse=True))

输出:

[[4, 1.25], [5, 1.2], [3, 0.66666666666666663], [2, 0.5]]
BrokenBenchmark
Reply   •   2 楼
BrokenBenchmark    3 年前

可以将关键参数传递给 .sort() .

在当前代码下面,添加:

ratio.sort(key=lambda x: x[1])

按比率排序(与默认排序机制相反,默认排序机制从列表中的第一个元素开始)。

在这次分拣操作之后, ratio 将:

[[2, 0.5], [3, 0.6666666666666666], [5, 1.2], [4, 1.25]]