Many-to-one mapping (creating equivalence classes)

后端 未结 4 785
花落未央
花落未央 2020-12-31 07:08

I have a project of converting one database to another. One of the original database columns defines the row\'s category. This column should be mapped to a new category in t

4条回答
  •  悲哀的现实
    2020-12-31 08:00

    You could override dict's indexer, but perhaps the following simpler solution would be better:

    >>> assoc_list = ( (('parrot','spam','cheese_shop'), 'sketch'), (('Cleese', 'Gilliam', 'Palin'), 'actors') )
    >>> equiv_dict = dict()
    >>> for keys, value in assoc_list:
        for key in keys:
            equiv_dict[key] = value
    
    
    >>> equiv_dict['parrot']
    'sketch'
    >>> equiv_dict['spam']
    'sketch'
    

    (Perhaps the nested for loop can be compressed an impressive one-liner, but this works and is readable.)

提交回复
热议问题