簡體   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