Mon*_*e27 0 python sorting dictionary tuples
def check():
dict_choice_a = {(a, b) : value, (b, a) : value} #(a, b) and (b, a) refer to the same value but repeted
dict_choice_b = {tuple(sorted((a, b)) : value} #not repetitive but unreadable
dict_choice_a[(a, b)] = new_value #need to do twice to change value but more readable than dict_choice_b
dict_choice_a[(b, a)] = new_value
#value of both keys are always the same
Run Code Online (Sandbox Code Playgroud)
我想创建一个dictionary引用其值的元组键,该键需要可交换,(a, b) = (b, a)并且它们只引用相同的值。
这里的问题是:使密钥的 tulpe 元素可交换但也引用相同值的最佳方法是什么。
此外,字符串也应该在解决方案中起作用。
根据评论,您可以将a和b放入frozenset无序的 a 中:
dict_choice = {frozenset((a, b)): value}
Run Code Online (Sandbox Code Playgroud)
如果您需要这是自动的,您可以创建自己的MutableMapping:
class MyDict(MutableMapping):
def __init__(self, arg=None):
self._map = {}
if arg is not None:
self.update(arg)
def __getitem__(self, key):
return self._map[frozenset(key)]
def __setitem__(self, key, value):
self._map[frozenset(key)] = value
def __delitem__(self, key):
del self._map[frozenset(key)]
def __iter__(self):
return iter(self._map)
def __len__(self):
return len(self._map)
Run Code Online (Sandbox Code Playgroud)
正在使用:
>>> d = MyDict([((1, 2), 'hello'), ((3, 4), 'world')])
>>> d[(2, 1)]
'hello'
Run Code Online (Sandbox Code Playgroud)
但是请注意,这可能会对其他类型的键产生意外行为:
>>> d['hello'] = 'world'
>>> d['hole']
'world'
>>> d[1] = 2
Traceback (most recent call last):
File "python", line 1, in <module>
File "python", line 14, in __setitem__
TypeError: 'int' object is not iterable
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
631 次 |
| 最近记录: |