简体   繁体   English

按多个项目排序一个dicts列表,为每个项目排序不同的反向值

[英]Sort a list of dicts by multiple items AND different reverse values for each item

I have the following list of objects and I want to sort them such that first all dicts with k2 == True (alphabetically ordered AZ) and afterwards all dicts with k2 == False (alphabetically ordered AZ). 我有以下对象列表,我想对它们进行排序,以便首先使用k2 == True (按字母顺序排列AZ)的所有dicts,然后使用k2 == False (按字母顺序排列的AZ)的所有dicts。 I tried something like this sorted(test, key=lambda k: (k['k2'], k['k1'].lower()), reverse=(True,False)) but it doesn't work. 我试过像这样的东西sorted(test, key=lambda k: (k['k2'], k['k1'].lower()), reverse=(True,False))但它不起作用。

>>> test = [
...     {"k1": "qsd", "k2": True},
...     {"k1": "JKd", "k2": False},
...     {"k1": "Ukz", "k2": False},
...     {"k1": "aqd", "k2": True},
...     {"k1": "Asd", "k2": True},
...     {"k1": "wef", "k2": False},
...     {"k1": "Wgr", "k2": True},
...     {"k1": "weg", "k2": False},
...     {"k1": "lfe", "k2": True},
... ]
>>>
>>> test = sorted(test, key=lambda k: (k['k2'], k['k1'].lower()), reverse=True)
>>> for t in test:
...     print(t)
...
{'k1': 'Wgr', 'k2': True}
{'k1': 'qsd', 'k2': True}
{'k1': 'lfe', 'k2': True}
{'k1': 'Asd', 'k2': True}
{'k1': 'aqd', 'k2': True}
{'k1': 'weg', 'k2': False}
{'k1': 'wef', 'k2': False}
{'k1': 'Ukz', 'k2': False}
{'k1': 'JKd', 'k2': False}

I'm looking for: 我在找:

{'k1': 'aqd', 'k2': True}
{'k1': 'Asd', 'k2': True}
{'k1': 'lfe', 'k2': True}
{'k1': 'qsd', 'k2': True}
{'k1': 'Wgr', 'k2': True}
{'k1': 'JKd', 'k2': False}
{'k1': 'Ukz', 'k2': False}
{'k1': 'wef', 'k2': False}
{'k1': 'weg', 'k2': False}

You're close, use not k['k2'] for the first sorter. 你很接近, not k['k2']使用not k['k2']作为第一台分拣机。

>>> test.sort(key=lambda k: (not k['k2'], k['k1'].lower()))
>>> test
[{'k1': 'aqd', 'k2': True},
 {'k1': 'Asd', 'k2': True},
 {'k1': 'lfe', 'k2': True},
 {'k1': 'qsd', 'k2': True},
 {'k1': 'Wgr', 'k2': True},
 {'k1': 'JKd', 'k2': False},
 {'k1': 'Ukz', 'k2': False},
 {'k1': 'wef', 'k2': False},
 {'k1': 'weg', 'k2': False}]

not k['k2'] is False when k['k2'] is True, and False (=0) < True (=1). not k['k2']Falsek['k2']为True,和False(= 0)<真(= 1)。

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

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