python - 如何按权重对两个成对元素的列表进行排序?

标签 python algorithm sorting

我正在处理这样的问题:

if __name__ == "__main__":
    data = list(map(int, sys.stdin.read().split()))
    n, capacity = data[0:2]
    elem1 = data[2:(2 * n + 2):2]
    elem2 = data[3:(2 * n + 2):2]
    ziplist = list(zip(values,weights))
    opt_value = get_optimal_value(capacity, elem1, elem2)

所以,当我打字的时候

3 40
20 40
50 60
70 80

我得到了这样的列表

[(20, 40), (50, 60), (70, 80)]

我需要按“权重”的值对我的列表进行排序,其中权重是

elem1/elem2

在测试的时候,我做了这样的列表

m = list(x/y for x,y in ziplist)     
[0.5, 0.8333333333333334, 0.875]

而且我看到最后一个元素具有最佳权重,因此我需要按如下方式对初始列表进行排序:

[(70, 80), (50, 60), (20, 40)]

我正在阅读有关使用键排序的内容,但我无法理解如何编写我的适当条件,类似的东西

 newlist = ziplist.sort(key=lambda m = x/y for x, y in ziplist m)

此外,我如何使用我的排序列表才能从第一个索引中获取 elem2。所以,我有这样的排序列表:

[(70, 80), (50, 60), (20, 40)]
#code implementation 

a = 70 #output
b = 80 #output

最佳答案

排序(l, key=lambda elem: elem[0]/elem[1], reverse=True)

关于python - 如何按权重对两个成对元素的列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36618256/

相关文章:

python - Python set 比 list 更节省空间吗?

algorithm - 查找图中从起始节点到结束节点的所有路径

algorithm - 以下方法的 Big-O 复杂度是多少?

algorithm - 最小覆盖圈

sorting - 为什么我们不能在合并排序中将数组划分 5 次?

vba - 按行排序

arrays - .sorted(by : ) method) 中的括号

Python 类型错误 : unsupported operand type(s) for ^: 'float' and 'int'

python - 在 flask 中,我应该手动捕获 View 中所有可能的错误吗?

python - pyinstaller 不使用 --onefile 捆绑 pyd 和 dll 文件