对元组的一个元素进行排序,而其他元素保持不变

时间:2020-09-24 14:15:50

标签: python python-3.x

w = [10,20, 30, 40, 50]
v = [20, 30, 66, 40, 60]

ratio = []
for i in range(len(w)):
    item = v[i]/w[i]
    ratio.append(item)

# making a tupe of ratio and weight
w_ratio = tuple(zip(ratio,w))

我想对比率进行排序,而权重应保持与之相关。我想要这个:

((2.2,30),(2,10),(1.5,20),(1.2,50),(1,40)) 

2 个答案:

答案 0 :(得分:2)

您可以使用参数sorted将元组传递到reverse=True,以指定降序。

>>> w = [10, 20, 30, 40, 50]
>>> v = [20, 30, 66, 40, 60]
>>> ratio = [i/j for i,j in zip(v,w)]
>>> sorted(zip(ratio, w), reverse=True)
[(2.2, 30), (2.0, 10), (1.5, 20), (1.2, 50), (1.0, 40)]

答案 1 :(得分:0)

sorted是您所需要的。

w = [10,20, 30, 40, 50]
v = [20, 30, 66, 40, 60]

ratio = []
for i in range(len(w)):
    item = v[i]/w[i]
    ratio.append(item)
w_ratio = tuple(zip(ratio, w))
w_ratio = sorted(w_ratio, reverse = True)

输出

[(2.2,30),(2.0,10),(1.5,20),(1.2,50),(1.0,40)]