Python中是否有“multimap”实现? [英] Is there a 'multimap' implementation in Python?

查看:402
本文介绍了Python中是否有“multimap”实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,我熟悉 Multimaps 其他 语言。 Python是否具有内置的这种数据结构,或者在常用的库中可用?

I am new to Python, and I am familiar with implementations of Multimaps in other languages. Does Python have such a data structure built-in, or available in a commonly-used library?

为了说明multimap的含义:

To illustrate what I mean by "multimap":

a = multidict()
a[1] = 'a'
a[1] = 'b'
a[2] = 'c'

print(a[1])  # prints: ['a', 'b']
print(a[2])  # prints: ['c']


推荐答案

这样的事情不存在于标准库。您可以使用 defaultdict 虽然:

Such a thing is not present in the standard library. You can use a defaultdict though:

>>> from collections import defaultdict
>>> md = defaultdict(list)
>>> md[1].append('a')
>>> md[1].append('b')
>>> md[2].append('c')
>>> md[1]
['a', 'b']
>>> md[2]
['c']

(而不是列表您可能需要使用设置,在这种情况下,您可以调用 .add 而不是 .append 。)

(Instead of list you may want to use set, in which case you'd call .add instead of .append.)

As另见:看看你写的这两行:

As an aside: look at these two lines you wrote:

a[1] = 'a'
a[1] = 'b'

这似乎表明你想要表达式 a [1] 等于两个不同的值。字典是不可能的,因为它们的键是唯一的,它们中的每一个都与一个值相关联。然而,您可以可以逐个提取与给定键相关联的列表内的所有值。您可以使用 iter ,然后连续调用 next 。或者你可以使用两个循环:

This seems to indicate that you want the expression a[1] to be equal to two distinct values. This is not possible with dictionaries because their keys are unique and each of them is associated with a single value. What you can do, however, is extract all values inside the list associated with a given key, one by one. You can use iter followed by successive calls to next for that. Or you can just use two loops:

>>> for k, v in md.items():
...     for w in v:
...         print("md[%d] = '%s'" % (k, w))
... 
md[1] = 'a'
md[1] = 'b'
md[2] = 'c'

这篇关于Python中是否有“multimap”实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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