我有一个这种形式的列表列表,我想根据值(1.0,2.0,3.0等)对其进行排序。是否有可以使用的python模块?
class_list= [['Image_3', '3.0'], ['Image_7', '7.0'], ['Image_4', '4.0'],
['Image_8', '8.0'], ['Image_1', '1.0'], ['Image_5', '5.0'],
['Image_6', '6.0'], ['Image_2', '2.0']]
答案 0 :(得分:1)
您可以尝试下面的
>>> class_list= [['Image_3', '3.0'], ['Image_7', '7.0'], ['Image_4', '4.0'],
['Image_8', '8.0'], ['Image_1', '1.0'], ['Image_5', '5.0'],
['Image_6', '6.0'], ['Image_2', '2.0']]
>>> sorted(class_list, key=lambda x: float(x[1]))
[['Image_1', '1.0'], ['Image_2', '2.0'], ['Image_3', '3.0'], ['Image_4', '4.0'], ['Image_5', '5.0'], ['Image_6', '6.0'], ['Image_7', '7.0'], ['Image_8', '8.0']]
您需要在排序时将第二个值的数据类型转换为float,否则它将执行字符串排序而不是数字排序。