Snippet for cleaning vertex groups

Here is a little snippet from a vacuum cleaner addon I’m putting together that I thought I’d post because I’ve found it pretty handy and couldn’t find a quick way to do this

Sometimes when you join objects and forget to clear vertex groups first you end up with a whole lot of unnecessary vgroups, and when weight painting often end up with a whole lot of zero weight vertices…

Went the loop thru verts first going thru groups then verts would give a nicer vert list to delete but it seemed to me that this way involved going thru verts only once.

import bpy


TOL = 0.001

meshobj = bpy.context.active_object
mode = meshobj.mode

# remove unwanted vertex-groups
# remove vertex groups that aren't in the keep collection
keep = ["jaw","upper_mouth","lower_mouth","eyelid.L","head"]

for vg in meshobj.vertex_groups:
    if vg.name not in keep:
        print(vg.name)
        meshobj.vertex_groups.remove(vg)
        
# remove all verts with weight less than TOL in vertex groups.        
     
mesh = meshobj.data



bpy.ops.object.mode_set(mode='OBJECT')
for vert in mesh.vertices :
    for vertgroup in vert.groups:
        verts_toremove = []
        if vertgroup.weight < TOL:
            verts_toremove.append(vert.index)
        if len(verts_toremove):
            meshobj.vertex_groups[vertgroup.group].remove(verts_toremove)  

bpy.ops.object.mode_set(mode=mode)