如何根据浮点列表对嵌套列表排序?解决zip方法报错问题
问题解决方法
首先你的代码存在两个关键问题,逐一解决如下:
1. 列表A的语法错误
你定义A时,子列表之间缺少逗号,这会直接导致语法报错。正确的定义应该是:
A = [[1.1,2.0,3.3], [3.8,50.9,1.0], [25.2,6.2,2.2]] B = [14.4, 0.1, 7.2]
2. 排序错误的原因与解决
你遇到的ValueError: The truth value of an array with more than one element is ambiguous,大概率是因为你实际使用的是numpy数组而非普通Python列表(普通列表用你的zip排序代码不会报错)。
情况一:使用普通Python列表
修正A的语法后,你的代码可以正常运行,还能同时生成排序后的B:
A = [[1.1,2.0,3.3], [3.8,50.9,1.0], [25.2,6.2,2.2]] B = [14.4, 0.1, 7.2] # 对B和A的配对进行排序 sorted_pairs = sorted(zip(B, A)) # 拆分得到排序后的结果 sorted_B = [b for b, _ in sorted_pairs] sorted_A = [a for _, a in sorted_pairs] print(sorted_A) # 输出: [[3.8, 50.9, 1.0], [25.2, 6.2, 2.2], [1.1, 2.0, 3.3]] print(sorted_B) # 输出: [0.1, 7.2, 14.4]
情况二:使用numpy数组
如果A和B是numpy数组,不能直接用sorted(zip(...)),需要用numpy的argsort方法获取排序索引,再重新索引数组:
import numpy as np A = np.array([[1.1,2.0,3.3], [3.8,50.9,1.0], [25.2,6.2,2.2]]) B = np.array([14.4, 0.1, 7.2]) # 获取B升序排序对应的索引 sorted_indices = np.argsort(B) # 根据索引重新排序A和B sorted_A = A[sorted_indices] sorted_B = B[sorted_indices] print(sorted_A) # 输出: # [[ 3.8 50.9 1.0] # [25.2 6.2 2.2] # [ 1.1 2.0 3.3]] print(sorted_B) # 输出: [0.1 7.2 14.4]
错误原因说明
当A是numpy数组时,zip(B, A)生成的元素是(numpy标量, numpy数组),排序时需要比较这些元素对。而numpy数组之间的比较会返回布尔数组,Python无法将布尔数组直接作为真值判断,因此抛出该错误。
内容的提问来源于stack exchange,提问作者ogclifford
相关产品推荐
相关产品推荐

