简体   繁体   English

Python的字典排序列表,最后为零值

[英]Python sort list of dictionary with zero values at the end

I have homogeneous list of dictionary with zero values, but it can contain any type of values. 我有一个零值的同义字典列表,但它可以包含任何类型的值。 Example: 例:

values=[{'buy_qty': 15, 'product_id': 30}, {'buy_qty': 0,'product_id': 33},{'buy_qty': 25, 'product_id': 50}, {'buy_qty': 7, 'product_id': 22}]

Is there way without reinventing the wheel to get list sorted by 'minimum "buy_qty" usual for python way, but "zero" values at the end of the list, like that: 有没有办法没有重新发明轮子获取列表排序的'最小'buy_qty“通常为python方式,但列表末尾的”零“值,如下所示:

values=[{'buy_qty': 7, 'product_id': 22}, {'buy_qty': 15, 'product_id': 30}, {'buy_qty': 25, 'product_id': 50}, {'buy_qty': 0,'product_id': 33}]

I have tried with itemgetter, 我试过过itemgetter,

sorted(total_lines, key=itemgetter('buy_qty'))

I feel like here can be some trick with "key" parameter 我觉得这里可以使用“key”参数进行一些技巧

You're right about the key function. 关键功能你是对的。 I added a key function that sorts by buy_qty, except if it's not greater than zero to then treat it as infinity, essentially moving it to the end. 我添加了一个按buy_qty排序的关键函数,除非它不大于零然后将其视为无穷大,基本上将其移至最后。

 sorted(values, key = lambda x: x['buy_qty'] if x['buy_qty'] > 0 else float('inf'))

You can define any function to use as sort - either outside of the sorted or inside using a lambda. 您可以定义要用作排序的任何函数 - 在sorted之外或使用lambda sorted在内部。 That way, you can make exceptions (in this case for the 0 quantity) 这样,您可以设置例外(在这种情况下为0数量)

 sorted(values, key=lambda x: x['buy_qty'] if x['buy_qty'] > 0 else float('Inf'))

Use a custom compare function. 使用自定义比较功能。

def custom_comparator(item1, item2):
    if item1 == item2:
            return 0
    elif 0 < item1 < item2 or item2 == 0:
            return -1
    else:
            return 1

 sorted(total_lines, cmp=custom_comparator, key=itemgetter('buy_qty'))

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

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