Home > Enterprise >  Python list comprehension with objects
Python list comprehension with objects

Time:01-20

I am trying to create a list of the following form

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

When using list comprehension or know this method

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

So what I get is a string but I need the variable.

Just to add some more background info. I am using Ansys SpaceClaim which have a scripting function to create geometry. When I select bodies I get the following

# 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)

So i would like to substitute that with somehing like

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

btw I can see I am also missing the last bodie

CodePudding user response:

You can use a list comprehension to iterate over a certain range:

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

After your edit:

# 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)
  •  Tags:  
  • Related