2

I have created this function to get the weights from a group:

def get_weights(ob, vgroup):
    weights = []
    for index, vert in enumerate(ob.data.vertices):
        for group in vert.groups:
            if group.group == vgroup.index:
                weights.append([index, group.weight])
    return weights

Is there any better more efficient way to do this?

ideasman42
  • 47,387
  • 10
  • 141
  • 223
Gaia Clary
  • 3,802
  • 2
  • 24
  • 39

1 Answers1

4

For The RNA mesh API, your example is quite good, one minor change you can make is to break once the group index is found.

Instead of making a large list, you could use a generator function, this can save memory for the cases you can iterate over the elements, and be converted to a list or tuple if you need, it has the same worst-case time, but in practice will often save some looping.

import bpy
obj = bpy.context.object

def get_weights(ob, vgroup):
    group_index = vgroup.index
    for i, v in enumerate(ob.data.vertices):
        for g in v.groups:
            if g.group == group_index:
                yield (i, g.weight)
                break

import bpy
obj = bpy.context.object
vgroup = obj.vertex_groups[0]

# iterate over index, weights
for i, w in get_weights(obj, vgroup):
    print(i, w)

# if you need as a list...
weights = list(get_weights(obj, vgroup))
print(weights)

Note, in some similar cases to this, you can use list-comprehension, however having to check the vertex is in the group causes the checks within the list-comprehension to become quite convoluted, so best avoid in this case.

ideasman42
  • 47,387
  • 10
  • 141
  • 223