Rename Levels based on LevelType Names + Elevation

Rename Levels based on LevelType Names + Elevation

I was setting up a project and needed to rename a bunch of levels quickly to include the correct suffix.

Here is the code sample that you can use:

# -*- coding: utf-8 -*-
#⬇️ Imports
from Autodesk.Revit.DB import *

#📦 Variables
uidoc = __revit__.ActiveUIDocument
doc   = __revit__.ActiveUIDocument.Document

#🎯 Main

# Sort Levels by Keywords in TypeName 
levels = FilteredElementCollector(doc).OfClass(Level).ToElements()
FF  = [lvl for lvl in levels if 'FBOK' in Element.Name.GetValue(doc.GetElement(lvl.GetTypeId()))] # Finish Floor
TOS = [lvl for lvl in levels if 'DOK'  in Element.Name.GetValue(doc.GetElement(lvl.GetTypeId()))] # Top of Structure
BOS = [lvl for lvl in levels if 'DUK'  in Element.Name.GetValue(doc.GetElement(lvl.GetTypeId()))] # Bottom of Structure

# Sort Levels by Elevation
FF.sort(key=lambda x: x.Elevation)
TOS.sort(key=lambda x: x.Elevation)
BOS.sort(key=lambda x: x.Elevation)

# Rename Levels
t = Transaction(doc, 'Rename Levels')
t.Start()

#
def rename_levels(levels, suffix):
    """Function to rename set of levels with the correct suffix."""
    for n, lvl in enumerate(levels):
        new_name = '{:02d} Floor_{}'.format(n, suffix)
        for i in range(10):
            try:    lvl.Name = new_name
            except: new_name += '*'

# Rename Levels
rename_levels(FF, 'FF')
rename_levels(TOS, 'TOS')
rename_levels(BOS, 'BOS')

t.Commit()


P.S.
I've made a one-liner, but in case you find it hard to read, here is how to extend it for easier understanding.

# One-Liner
FF  = [lvl for lvl in levels if 'FBOK' in Element.Name.GetValue(doc.GetElement(lvl.GetTypeId()))] # Finish Floor

# Simple Python
FF = []
for lvl in levels:
    lvl_type = doc.GetElement(lvl.GetTypeId())
    lvl_type_name = Element.Name.GetValue(lvl_type)
    if 'FBOK' in lvl_type_name:
        FF.append(lvl)


And here is a visual example.

⌨️ Happy Coding!
Erik Frits