如何将具有多个键的字典制作为一个值? [英] How do I make a dictionary with multiple keys to one value?
本文介绍了如何将具有多个键的字典制作为一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
dictionary = {('a','b' ):1,('c','d'):2}
任何想法? p>
解决方案
我想你的意思是:
class Value:
def __init __(self,v = None):
self.v = v
v1 = Value(1)
v2 = Value (2)
d = {'a':v1,'b':v1,'c':v2,'d':v2}
d ['a']。v + 1
d ['b']。v == 2#True
- Python的字符串和数字是不可变的对象,
- 所以,如果你想要
d ['a']
和d ['b']
指向与更新相同的值,因为它会更改,值指的是可变对象(用户定义的类,如上所述,或dict
,列表
,set
)。 - 然后,当您修改
d ['a']
,d ['b']
同时更改,因为它们都指向相同的对象。
I have a question about a dictionary I want to make. My goal is to have multiple keys to a single value,like below:
dictionary={('a','b'):1,('c','d'):2}
Any ideas?
解决方案
I guess you mean this:
class Value:
def __init__(self, v=None):
self.v = v
v1 = Value(1)
v2 = Value(2)
d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1
d['b'].v == 2 # True
- Python's strings and numbers are immutable objects,
- So, if you want
d['a']
andd['b']
to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or adict
,list
,set
). - Then, when you modify the object at
d['a']
,d['b']
changes at same time because they both point to same object.
这篇关于如何将具有多个键的字典制作为一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文