【问题标题】:Python list comprehension with objects带有对象的 Python 列表理解
【发布时间】:2022-01-20 10:43:36
【问题描述】:

我正在尝试创建以下表单的列表

a = [group[0],
     group[1],
     group[2]]

当使用列表推导或者知道这个方法时

a = ['group[{}]'.format(i) for i in range(3)]
a = ['group[0]',
     'group[1]',
     'group[2]']

所以我得到的是一个字符串,但我需要变量。

只是为了添加更多背景信息。我正在使用 Ansys SpaceClaim,它具有创建几何的脚本功能。当我选择身体时,我得到以下内容

# Merge Bodies
no_bodies = GetRootPart().Components[0].Components.Count

targets = BodySelection.Create([GetRootPart().Components[0].Components[0].Content.Bodies[0],
GetRootPart().Components[0].Components[1].Content.Bodies[0],
GetRootPart().Components[0].Components[2].Content.Bodies[0],
GetRootPart().Bodies[0]])
result = Combine.Merge(targets, Info1)

所以我想用类似的东西代替它

    targets = BodySelection.Create([GetRootPart().Components[0].Components[i].Content.Bodies[0] for i in range(3)])

顺便说一句,我可以看到我也错过了最后一个身体

【问题讨论】:

  • a = [group[0], group[1], group[2]] 只是a = group[0:3]
  • 是的,我一开始就不清楚。我已经修改了问题,因此它显示了使用的代码。如您所见,它是 group[0].body[0]、group[1].body[0] 等
  • 我还编辑了我的答案,应该使用理解并添加两个列表。

标签: python list variables list-comprehension


【解决方案1】:

您可以使用列表推导来迭代特定范围:

BodySelection.Create([
    GetRootPart().Components[0].Components[i].Content.Bodies[0]
    for i in range(3)
])

修改后:

# Merge Bodies
no_bodies = GetRootPart().Components[0].Components.Count

targets = BodySelection.Create(
    [
        GetRootPart().Components[0].Components[i].Content.Bodies[0]
        for i in range(3)
    ]
    + [GetRootPart().Bodies[0]]
)
result = Combine.Merge(targets, Info1)

【讨论】:

  • 谢谢,我以为我尝试了第一件事,显然我没有。因为它正在工作:)
猜你喜欢
  • 1970-01-01
  • 2015-03-31
  • 2020-05-29
  • 2020-01-07
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 2017-02-08
相关资源
最近更新 更多