当按列表的不同属性排序时,如何确定列表顺序是否更改?

时间:2018-11-20 08:42:38

标签: python

如果我有字典列表,并按两个不同的键对列表进行排序,那么如何确定两个键的结果列表顺序是否相同?

例如,我有一个列表,例如:

rename_operations = [
    {'before_rename': 'DSCF_1.jpg', 'after_rename': '20181200_123112.jpg'},
    {'before_rename': 'DSCF_2.jpg', 'after_rename': '20181200_123212.jpg'},
    {'before_rename': 'DSCF_3.jpg', 'after_rename': '20181200_123312.jpg'},
    {'before_rename': 'DSCF_4.jpg', 'after_rename': '20181200_123412.jpg'},
    {'before_rename': 'DSCF_5.jpg', 'after_rename': '20181200_123512.jpg'},
]

我想验证一下,在两种情况下都按before_renameafter_rename对列表进行排序会以相同的顺序产生列表。

1 个答案:

答案 0 :(得分:1)

我相信您可以只使用==

rename_operations1 = [
    {'before_rename': 'DSCF_1.jpg', 'after_rename': '20181200_123112.jpg'},
    {'before_rename': 'DSCF_2.jpg', 'after_rename': '20181200_123212.jpg'},
    {'before_rename': 'DSCF_3.jpg', 'after_rename': '20181200_123312.jpg'},
    {'before_rename': 'DSCF_4.jpg', 'after_rename': '20181200_123412.jpg'},
    {'before_rename': 'DSCF_5.jpg', 'after_rename': '20181200_123512.jpg'},
]

rename_operations2 = [
    {'before_rename': 'DSCF_1.jpg', 'after_rename': '20181200_123112.jpg'},
    {'before_rename': 'DSCF_3.jpg', 'after_rename': '20181200_123312.jpg'},
    {'before_rename': 'DSCF_4.jpg', 'after_rename': '20181200_123412.jpg'},
    {'before_rename': 'DSCF_5.jpg', 'after_rename': '20181200_123512.jpg'},
    {'before_rename': 'DSCF_2.jpg', 'after_rename': '20181200_123212.jpg'},
]

print(rename_operations1 == rename_operations2)
>>> False

print(rename_operations1 == rename_operations1)
>>> True