Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 按列表中的值对嵌套字典列表进行排序_Python 3.x_Sorting_Dictionary - Fatal编程技术网

Python 3.x 按列表中的值对嵌套字典列表进行排序

Python 3.x 按列表中的值对嵌套字典列表进行排序,python-3.x,sorting,dictionary,Python 3.x,Sorting,Dictionary,我正在尝试使用 [OrderedDict([('id', 1), ('events', [OrderedDict([('id', 4), ('timestamp', '2018-01-19T15:47:56.587126Z')]), OrderedDict([('id', 5), ('timestamp', '2018-01-19T15:47:56.587761Z')])])]), OrderedDict([('id',

我正在尝试使用

[OrderedDict([('id', 1), ('events', [OrderedDict([('id', 4), ('timestamp', '2018-01-19T15:47:56.587126Z')]),
                                     OrderedDict([('id', 5), ('timestamp', '2018-01-19T15:47:56.587761Z')])])]),
 OrderedDict([('id', 2), ('events', [OrderedDict([('id', 6), ('timestamp', '2018-01-19T15:47:56.588413Z')])])])]
但这仅在“事件”下的列表长度为1时有效。如果我做了reverse=False,我会得到正确的顺序(只是向后),但我需要最新的时间戳

编辑:

我尝试获取的排序的时间戳顺序如下:

sorted(my_list, key=lambda e: e['events'][0]['timestamp'], reverse=True)

似乎您希望反转OrderedDicts列表以及任何嵌套列表。我们可以通过反向重新创建列表来实现这一点

代码

('timestamp', '2018-01-19T15:47:56.588413Z')
('timestamp', '2018-01-19T15:47:56.587761Z')
('timestamp', '2018-01-19T15:47:56.587126Z')
输出

def reversed_nested_list(lst):
    """Return a reversed list of shallow nested OrderedDicts."""
    main_lst = []
    for od in lst[::-1]:
        replaced = ct.OrderedDict()
        for k, v in od.items():
            if not isinstance(v, list):
                replaced[k] = v
            else:
                replaced[k] = v[::-1]
        main_lst.append(replaced)
    return main_lst


reversed_nested_list(my_list)

由于您的事件已按时间顺序插入,我们只需迭代主列表,然后反向重新分配任何嵌套列表。

请参见下面的答案。我正在尝试将最近的时间戳设置为最早的时间戳。我可以使用我拥有的从最旧到最新,但是如果我颠倒列表,从最新到最旧,它会改变周围的顺序,你想按最新的时间戳排序吗?请发布例外结果。您是否只对时间戳或我帖子中显示的输出感兴趣?
[OrderedDict([('id', 2),
              ('events',
               [OrderedDict([('id', 6),
                             ('timestamp',
                              '2018-01-19T15:47:56.588413Z')])])]),
 OrderedDict([('id', 1),
              ('events',
               [OrderedDict([('id', 5),
                             ('timestamp', '2018-01-19T15:47:56.587761Z')]),
                OrderedDict([('id', 4),
                             ('timestamp',
                              '2018-01-19T15:47:56.587126Z')])])])]