How to I factorize a list of tuples?

后端 未结 6 2021
春和景丽
春和景丽 2020-12-06 10:43

definition
factorize: Map each unique object into a unique integer. Typically, the range of integers mapped to is from zero to the n - 1 where n is

6条回答
  •  一个人的身影
    2020-12-06 11:00

    A simple way to do it is use a dict to hold previous visits:

    >>> d = {}
    >>> [d.setdefault(tup, i) for i, tup in enumerate(tups)]
    [0, 1, 2, 3, 4, 1, 2]
    

    If you need to keep the numbers sequential then a slight change:

    >>> from itertools import count
    >>> c = count()
    >>> [d[tup] if tup in d else d.setdefault(tup, next(c)) for tup in tups]
    [0, 1, 2, 3, 4, 1, 2, 5]
    

    Or alternatively written:

    >>> [d.get(tup) or d.setdefault(tup, next(c)) for tup in tups]
    [0, 1, 2, 3, 4, 1, 2, 5]
    

提交回复
热议问题