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()可以對其他數據結構排序。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM