Assign strings to IDs in Python -
i reading text file python, formatted values in each column may numeric or strings.
when values strings, need assign unique id of string (unique across strings under same column; same id must assigned if same string appears elsewhere under same column).
what efficient way it?
use defaultdict default value factory generates new ids:
ids = collections.defaultdict(itertools.count().next) ids['a'] # 0 ids['b'] # 1 ids['a'] # 0
when key in defaultdict, if it's not present, defaultdict calls user-provided default value factory value , stores before returning it.
collections.count()
creates iterator counts 0, collections.count().next
bound method produces new integer whenever call it.
combined, these tools produce dict returns new integer whenever you've never looked before.
Comments
Post a Comment