Python 对末尾为零值的字典列表进行排序

标签 python list sorting dictionary

我有零值字典的同类列表,但它可以包含任何类型的值。示例:

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}]

有没有办法在不重新发明轮子的情况下按 python 方式通常的“最小“buy_qty””排序列表,但在列表末尾有“零”值,就像这样:

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}]

我试过 itemgetter,

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

我觉得这里可以用“key”参数来搞点把戏

最佳答案

关于关键功能,你是对的。我添加了一个按 buy_qty 排序的关键函数,除非它不大于零然后将其视为无穷大,基本上将它移到最后。

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

关于Python 对末尾为零值的字典列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43258586/

相关文章:

php - 从结果计算日期的最佳方法?

Python按具有相同属性的列表中的相邻项目分组

algorithm - 仅使用推送和删除操作将列表从订单 A 修改为订单 B

javascript - 按升序显示多个 html 文本框值

linux - Linux下的Grep命令

arrays - Elm - 更新列表中的元素

python - 从字典列表中返回一个特定的字典

python - 如何让 pyuic4 自动将标签设置为 "MainWindow"?

python - 如何使用Python中的样式突出显示Excel中的标题?

python语义代理/服务器,使用哪个框架?