首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用Python语言编写Javascript recipe.components.sort((a,b) => (a.components ?1: 0) - (b.components ?1: 0))?

如何用Python语言编写Javascript recipe.components.sort((a,b) => (a.components ?1: 0) - (b.components ?1: 0))?
EN

Stack Overflow用户
提问于 2021-06-16 01:44:32
回答 1查看 64关注 0票数 0

我已经把一个程序从javascript翻译成了python3.9,我只是错过了结果的排序,但我就是不能再做下去了。

该列表由id为"components“的字典组成,该id本身就是一个列表。

代码语言:javascript
复制
recipe.components.sort((a, b) => (a.components ? 1 : 0) - (b.components ? 1 : 0))

如果我正确理解了java代码,那么作为空列表的所有元素(a.components)都应该在开头,在列表中有元素的所有元素都应该在末尾,但这是一个小问题,因为无论如何都可以用.reverse()颠倒它。

代码语言:javascript
复制
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写得最优雅?

-编辑

我是这样解决的:

代码语言:javascript
复制
recipe["components"].sort(key=lambda a: 1 if a.get("components") else 0)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-16 01:49:47

对于您的原始代码:

代码语言:javascript
复制
components.sort((a, b) => (a ? 1 : 0) - (b ? 1 : 0))

...it可以是:

代码语言:javascript
复制
components.sort(key=bool)

编辑后,请执行以下操作:

代码语言:javascript
复制
components.sort((a, b) => (a.components ? 1 : 0) - (b.components ? 1 : 0))

..。我将假设相应的Python列表包含属性为components的对象

代码语言:javascript
复制
components.sort(key=lambda a: bool(a.components))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67991155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档