Python:字典列表排序

 参考:https://www.runoob.com/python3/python-sort-dictionaries-by-key-or-value.html

if __name__ == '__main__':
    list = []
    for i in range(10):
        dict_time = {"time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
        list.append(dict_time)
        time.sleep(1)
    print(list)
    print(sorted(list, key=lambda i: i['time'], reverse=True))

sorted() 函数对所有可迭代的对象进行排序操作,key 是用来进行比较的元素

lambda 用于匿名函数,是固定写法,不要写成别的单词

i表示列表中的一个元素,在这里,表示一个字典,i只是临时起的一个名字,你可以使用任意的名字;i['time']这句命令的意思就是按照列表字典中的‘time’排序。默认升序,reverse=True表示降序 

上述代码输出结果:                                     

[{'time': '2020-09-18 18:04:08'}, {'time': '2020-09-18 18:04:09'}, {'time': '2020-09-18 18:04:10'}, {'time': '2020-09-18 18:04:11'}, {'time': '2020-09-18 18:04:12'}, {'time': '2020-09-18 18:04:13'}, {'time': '2020-09-18 18:04:14'}, {'time': '2020-09-18 18:04:15'}, {'time': '2020-09-18 18:04:16'}, {'time': '2020-09-18 18:04:17'}]
[{'time': '2020-09-18 18:04:17'}, {'time': '2020-09-18 18:04:16'}, {'time': '2020-09-18 18:04:15'}, {'time': '2020-09-18 18:04:14'}, {'time': '2020-09-18 18:04:13'}, {'time': '2020-09-18 18:04:12'}, {'time': '2020-09-18 18:04:11'}, {'time': '2020-09-18 18:04:10'}, {'time': '2020-09-18 18:04:09'}, {'time': '2020-09-18 18:04:08'}]

下面是sorted排序方法的详细解释:(感谢:https://blog.csdn.net/cxcxrs/article/details/82459800#%E4%B8%80%E3%80%81sorted%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0

1. sorted高阶函数语法格式:  sorted(可迭代对象,key=函数名,reverse=False/True)

     作用:从可迭代对象中,依次取出一个元素,该元素再按照key规定的排列依据排序。

     可迭代对象:即可依次取值的对象,例如:集合,序列(列表,字符串,元组),字典等。

     key : 是列表排列的依据,一般可以自定义一个函数返回排序的依据,再把函数名绑定给key。

     reverse : 译为反转,reverse默认等于False,从小到大排序。等于True时,从大到小排序。

2. 匿名函数lambda的格式:    函数名 = lambda  [形参1,形参2,...] :  ,返回操作语句块产生的结果并绑定给函数名。

例如: key=lambda x : x[1]       

            x:相当于字典集合中的一个元组, 例:dict_items([('a', 1), ('c', 3), ('b', 2)])中的('a', 1)或('c', 3)或('b', 2)

            x[1]: 返回x中的第二个元素,即键值对元组中的值。dict_items([('a', 1), ('c', 3), ('b', 2)])中的1或2或3

注意:

  (1) sorted函数中的可迭代对象不要用字典d,那样只能迭代出的字典d的键。要用d.items()才可迭代出字典的键值对。

    例:不能用 d_order=sorted(d,key=lambda x:x[1],reverse=False)

            要用 d_order=sorted(d.items(),key=lambda x:x[1],reverse=False)

  (2) sorted函数排好序后,要绑定一个对象(赋值),例:d_order=sorted(d.items(),key=lambda x:x[1],reverse=False).

     因为字典是无序类型,用sorted函数排好序后不绑定d_order,字典会自动打乱顺序。

猜你喜欢

转载自blog.csdn.net/weixin_38676276/article/details/108670611