有一个类似
的列表l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]
我想通过一个指定的键(例如n
)对其进行排序。
此外,密钥的某些值可能是None
,我想把它们留在后面
这是我的审判
l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]
from functools import partial
def order(key, item):
if item[key]:
return item[key]
else:
return 0
order_key = "n"
r = sorted(l, key=partial(order, order_key), reverse=True)
print(r)
有没有更好的方法来实现它?
答案 0 :(得分:4)
这是将sorted
与key
结合使用的一种方法:
sorted(l, key=lambda x: -x['n'] if x['n'] is not None else float('inf'))
[{'n': 3, 'm': None},
{'n': 1, 'm': 3},
{'n': None, 'm': 1},
{'n': None, 'm': 0}]
让我们再举一个例子:
l = [ {"n":1, "m":3}, {"n":None, "m":1}, {"n":3, "m":None}, {"n":None, "m":0},
{"n":0, "m":0}, {"n":-1, "m":0}]
sorted(l, key=lambda x: -x['n'] if x['n'] is not None else float('inf'))
[{'n': 3, 'm': None},
{'n': 1, 'm': 3},
{'n': 0, 'm': 0},
{'n': -1, 'm': 0},
{'n': None, 'm': 1},
{'n': None, 'm': 0}]
答案 1 :(得分:2)
使用返回双元组条件的键函数:
l = [ {"n":1, "m":3}, {"n":None, "m":1}, {"n":3, "m":None}, {"n":None, "m":0}]
result = sorted(l,key = lambda d : (d["m"] is None,d["m"] or 0))
结果:
>>> result
[{'m': 0, 'n': None},
{'m': 1, 'n': None},
{'m': 3, 'n': 1},
{'m': None, 'n': 3}]
让我们澄清一下它的工作方式和原因:
(d["m"] is None,d["m"] or 0)
是tuple
:
True
,如果第一个元素的值为None
,则保证None
个条目是最后一个(取反,取反)or
技巧将None
转换为0,因此它可以与其他没有错误的整数进行比较(尽管这里不需要,因为第一个布尔值会终止元组比较,所以我们可以写(d["m"] is None,d["m"])
)答案 2 :(得分:1)
l = [ {"n":1, "m":3}, {"n":None, "m":1}, {"n":3, "m":None}, {"n":None, "m":0}]
newlist = sorted(l, key=lambda k: (k['n'] is None, k['n'] == 0, k['n']), reverse = True)
print (newlist)
输出:
[{'n': None, 'm': 1}, {'n': None, 'm': 0}, {'n': 3, 'm': None}, {'n': 1, 'm': 3}]