python list排序

今天用到了list排序,list中为dic,下面记录一下排序的方法。

第一种:sort(),sort为list内建函数,它会改变list本身。

sort()的语法为:

list.sort(cmp=None, key=None, reverse=False)
  • cmp -- 可选参数, 如果指定了该参数会使用该参数的方法进行排序。
  • key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
  • reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。

使用方法为:

data = [
       {
            "chinese_name": "数据中心",
            "attribute_name": "bk_data_center",
             "weight": 7
        },

        {
            "chinese_name": "分组",
            "attribute_name": "objects_classifcation",
             "weight": 3
        },
        {
            "chinese_name": "类型",
            "attribute_name": "bk_obj_id",
            "weight": 4
        }
     ]

data.sort(key=lambda x: x['weight'])
print data
==>[
        {
            "chinese_name": "分组",
            "attribute_name": "objects_classifcation",
            "weight": 3
        },
        {
            "chinese_name": "类型",
            "attribute_name": "bk_obj_id",
            "weight": 4
        },
        {
            "chinese_name": "数据中心",
            "attribute_name": "bk_data_center",
            "weight": 7
        }]

第二种:使用python内置函数sorted排序。sorted不会改变原数组,会生成一个全新的数组。

使用方法如下:

data = [
       {
            "chinese_name": "数据中心",
            "attribute_name": "bk_data_center",
             "weight": 7
        },

        {
            "chinese_name": "分组",
            "attribute_name": "objects_classifcation",
             "weight": 3
        },
        {
            "chinese_name": "类型",
            "attribute_name": "bk_obj_id",
            "weight": 4
        }
     ]
result = sorted(data, key=lambda x: x['weight'])
print result
==>[
        {
            "chinese_name": "分组",
            "attribute_name": "objects_classifcation",
            "weight": 3
        },
        {
            "chinese_name": "类型",
            "attribute_name": "bk_obj_id",
            "weight": 4
        },
        {
            "chinese_name": "数据中心",
            "attribute_name": "bk_data_center",
            "weight": 7
        }]

list.sort()与sorted()的区别

1、list.sort()会改变原数组,而sorted()不会。

2、list.sort()只可对list进行排序,而sorted()可以对其他数据结构排序。

原文地址:https://www.cnblogs.com/wangyingblock/p/11340108.html