多对一映射(创建对等类) [英] Many-to-one mapping (creating equivalence classes)

查看:129
本文介绍了多对一映射(创建对等类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将一个数据库转换为另一个数据库的项目.原始数据库列之一定义了行的类别.此列应映射到新数据库中的新类别.

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 the new database.

例如,假设原始类别为:parrot, spam, cheese_shop, Cleese, Gilliam, Palin

For example, let's assume the original categories are:parrot, spam, cheese_shop, Cleese, Gilliam, Palin

现在这对我来说有点冗长,我想将这些行归类为sketch, actor-也就是说,将所有草图和所有角色定义为两个等效类.

Now that's a little verbose for me, And I want to have these rows categorized as sketch, actor - That is, define all the sketches and all the actors as two equivalence classes.

>>> monty={'parrot':'sketch', 'spam':'sketch', 'cheese_shop':'sketch', 
'Cleese':'actor', 'Gilliam':'actor', 'Palin':'actor'}
>>> monty
{'Gilliam': 'actor', 'Cleese': 'actor', 'parrot': 'sketch', 'spam': 'sketch', 
'Palin': 'actor', 'cheese_shop': 'sketch'}

那很尴尬-我更喜欢吃这样的东西:

That's quite awkward- I would prefer having something like:

monty={ ('parrot','spam','cheese_shop'): 'sketch', 
        ('Cleese', 'Gilliam', 'Palin') : 'actors'}

但是,这当然将整个元组设置为键:

But this, of course, sets the entire tuple as a key:

>>> monty['parrot']

Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    monty['parrot']
KeyError: 'parrot'

有什么想法如何在Python中创建优雅的多对一词典?

Any ideas how to create an elegant many-to-one dictionary in Python?

推荐答案

在我看来,您有两个问题.首先,您最初如何表示映射,即如何将映射键入到new_mapping.py文件中.第二,映射在重新映射过程中如何工作.这两个表示没有相同的理由.

It seems to me that you have two concerns. First, how do you express your mapping originally, that is, how do you type the mapping into your new_mapping.py file. Second, how does the mapping work during the re-mapping process. There's no reason for these two representations to be the same.

从您喜欢的映射开始:

monty = { 
    ('parrot','spam','cheese_shop'): 'sketch', 
    ('Cleese', 'Gilliam', 'Palin') : 'actors',
}

然后将其转换为所需的映射:

then convert it into the mapping you need:

working_monty = {}
for k, v in monty.items():
    for key in k:
        working_monty[key] = v

生产:

{'Gilliam': 'actors', 'Cleese': 'actors', 'parrot': 'sketch', 'spam': 'sketch', 'Palin': 'actors', 'cheese_shop': 'sketch'}

然后使用working_monty进行工作.

这篇关于多对一映射(创建对等类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆