我已经把一个程序从javascript翻译成了python3.9,我只是错过了结果的排序,但我就是不能再做下去了。
该列表由id为"components“的字典组成,该id本身就是一个列表。
recipe.components.sort((a, b) => (a.components ? 1 : 0) - (b.components ? 1 : 0))如果我正确理解了java代码,那么作为空列表的所有元素(a.components)都应该在开头,在列表中有元素的所有元素都应该在末尾,但这是一个小问题,因为无论如何都可以用.reverse()颠倒它。
recipe.components = [{
"id": 123,
"components": [{"id": 1, "components": []}]
},
{
"id": 124,
"components": [{"id": 2, "components": []}, {"id": 3, "components": []}]
},
{
"id": 125,
"components": []
},
{
"id": 126,
"components": [{"id": 1, "components": []}]
}]有没有人知道如何用Python写得最优雅?
-编辑
我是这样解决的:
recipe["components"].sort(key=lambda a: 1 if a.get("components") else 0)发布于 2021-06-16 01:49:47
对于您的原始代码:
components.sort((a, b) => (a ? 1 : 0) - (b ? 1 : 0))...it可以是:
components.sort(key=bool)编辑后,请执行以下操作:
components.sort((a, b) => (a.components ? 1 : 0) - (b.components ? 1 : 0))..。我将假设相应的Python列表包含属性为components的对象
components.sort(key=lambda a: bool(a.components))https://stackoverflow.com/questions/67991155
复制相似问题