如何按num列表对多个关联列表进行同序降序排序?
按关联列表值同步降序排序的解决方案
你有三个关联列表cod、desc、num,需要按num列表的值对三者进行同序降序排序,单独使用num.sort()无法实现同步排序的需求。
原代码
cod = [] desc = [] num =[] cod.append("1") desc.append("Product1") num.append(94) cod.append("2") desc.append("Product2") num.append(93) cod.append("3") desc.append("Product3") num.append(95) for row in range(len(cod)): print(cod[row], desc[row], num[row])
期望输出
3 Product3 95 1 Product1 94 2 Product2 93
解决方案
单独对num排序只会改变自身顺序,无法联动另外两个列表。可以通过zip()打包关联元素,再整体排序后解包的方式实现同步排序:
修改后的代码
cod = [] desc = [] num =[] cod.append("1") desc.append("Product1") num.append(94) cod.append("2") desc.append("Product2") num.append(93) cod.append("3") desc.append("Product3") num.append(95) # 打包三个列表并按num降序排序 sorted_items = sorted(zip(cod, desc, num), key=lambda x: x[2], reverse=True) # 解包回三个列表 cod_sorted, desc_sorted, num_sorted = zip(*sorted_items) # 输出结果 for c, d, n in zip(cod_sorted, desc_sorted, num_sorted): print(c, d, n)
代码说明
zip(cod, desc, num):将三个列表中对应位置的元素打包成元组,比如("1", "Product1", 94)sorted(..., key=lambda x: x[2], reverse=True):以元组中第三个元素(即num的值)为排序依据,reverse=True实现降序排列zip(*sorted_items):将排序后的元组序列解包,重新分配到三个新的排序后列表中
运行上述代码即可得到你期望的输出结果。
内容的提问来源于stack exchange,提问作者Brandalize
相关产品推荐
相关产品推荐

