繁体   English   中英

Python3中包含字典的列表的排序

[英]Sorting of list which contains dictionary in Python3

我有 2 个非常嵌套的 Python 字典,我想比较它们(我真正的 Json 文件包含数十万行)。 这些字典包含列表,而这些列表包含字典。 元素的顺序不是固定的,在字典的情况下不是问题,但在列表的情况下是问题。 所以我必须对结构中的元素进行排序。

我编写了一个排序算法,它在我的数据结构中递归地对项目进行排序。

我的代码与 Python2.7 可执行文件按预期工作,但它不适用于 Python3.6.6 可执行文件。

我已经阅读了官方的 Python 文档并且我知道list.sort()在 Python2 和 Python3 之间已经发生了变化,但我觉得它在 Python3 中是一个很大的限制。

我熟悉key参数,但它不能解决我的问题。 此外,字典中的键也不相同。

所以,我的问题:是否可以对包含更多类型元素的列表进行排序,例如我的情况?

代码:

test_1 = {"aaa": 111, "bbb": 222, "ccc": [{"o": [1, "t"]}, "a", "b", 1, [1, 2, [4, 3, [6, 5]]]]}
test_2 = {"bbb": 222, "aaa": 111, "ccc": [[2, 1, [3, 4, [5, 6]]], 1, "a", "b", {"o": ["t", 1]}]}


def list_sort(l):
    if isinstance(l, list):
        l.sort()
        for x in l:
            list_sort(x)


def dict_sorter(d):
    for k, v in d.items():
        if isinstance(v, dict):
            dict_sorter(v)
        elif isinstance(v, list):
            v.sort()
            for x in v:
                if isinstance(x, dict):
                    dict_sorter(x)
                elif isinstance(x, list):
                    list_sort(x)


print("\n\nBEFORE:")
print(test_1)
print(test_2)
print("EQ: {}".format(test_1 == test_2))

dict_sorter(test_1)
dict_sorter(test_2)

print("\n\nAFTER:")
print(test_1)
print(test_2)
print("EQ: {}".format(test_1 == test_2))

Output 与 Python2:

>>> python2 test.py

BEFORE:
{'aaa': 111, 'bbb': 222, 'ccc': [{'o': [1, 't']}, 'a', 'b', 1, [1, 2, [4, 3, [6, 5]]]]}
{'aaa': 111, 'bbb': 222, 'ccc': [[2, 1, [3, 4, [5, 6]]], 1, 'a', 'b', {'o': ['t', 1]}]}
EQ: False

AFTER:
{'aaa': 111, 'bbb': 222, 'ccc': [1, {'o': [1, 't']}, [1, 2, [3, 4, [5, 6]]], 'a', 'b']}
{'aaa': 111, 'bbb': 222, 'ccc': [1, {'o': [1, 't']}, [1, 2, [3, 4, [5, 6]]], 'a', 'b']}
EQ: True

Output 与 Python3:

>>> python3 test.py

BEFORE:
{'aaa': 111, 'bbb': 222, 'ccc': [{'o': [1, 't']}, 'a', 'b', 1, [1, 2, [4, 3, [6, 5]]]]}
{'bbb': 222, 'aaa': 111, 'ccc': [[2, 1, [3, 4, [5, 6]]], 1, 'a', 'b', {'o': ['t', 1]}]}
EQ: False
Traceback (most recent call last):
  File "test.py", line 30, in <module>
    dict_sorter(test_1)
  File "test.py", line 17, in dict_sorter
    v.sort()
TypeError: '<' not supported between instances of 'str' and 'dict'

在 python2 中,可以将任何数据与任何其他数据进行比较。 但是,在 python3 中这是不可能的。

[参考]

https://portingguide.readthedocs.io/en/latest/comparisons.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM