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

问题描述

我是 Python 新手,熟悉 Multimaps语言.Python 是否内置了这样的数据结构,或者在常用库中可用?

为了说明我所说的multimap"是什么意思:

a = multidict()a[1] = 'a'a[1] = 'b'[2] = 'c'打印(a[1]) # 打印:['a', 'b']打印(a[2]) # 打印:['c']
解决方案

这样的东西在标准库中是不存在的.您可以使用 defaultdict:

>>>从集合导入 defaultdict>>>md = defaultdict(列表)>>>md[1].append('a')>>>md[1].append('b')>>>md[2].append('c')>>>医学博士[1]['a', 'b']>>>医学博士[2]['C']

(您可能希望使用 set 而不是 list,在这种情况下,您将调用 .add 而不是 .追加.)

顺便说一句:看看你写的这两行:

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

这似乎表明您希望表达式 a[1] 等于两个不同的值.这对于字典是不可能的,因为它们的键是唯一的,并且每个键都与一个值相关联.但是,您可以做的是,将列表中与给定键关联的所有值一一提取.您可以使用 iter 后跟连续调用next.或者你可以只使用两个循环:

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

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?

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']
解决方案

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']

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


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

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

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"实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:36
查看更多