Skip to content

Instantly share code, notes, and snippets.

@benmaier
Created November 16, 2023 13:33
Show Gist options
  • Save benmaier/34727a01924fb37fba9f5e735980dee9 to your computer and use it in GitHub Desktop.
Save benmaier/34727a01924fb37fba9f5e735980dee9 to your computer and use it in GitHub Desktop.
Python class of a continuous label-to-integer mapping that converts labels to integer indices and automatically handles new labels
class IntLabel():
def __init__(self):
self.ints = {}
self.keys = []
super().__init__()
def __getitem__(self, key):
try:
return self.ints[key]
except KeyError:
i = len(self.ints)
self.keys.append(key)
self.ints[key] = i
return i
def inv(self,i):
return self.keys[i]
def __str__(self):
return str(self.ints)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment