【发布时间】:2017-05-06 16:23:42
【问题描述】:
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
我想创建一个 dictionary,其中包含引用其值的元组键,该键需要可交换为 (a, b) = (b, a),并且它们仅引用相同的值。
这里的问题是:使 tulpe of keys 的元素可交换但也引用相同值的最佳方法是什么。
此外,字符串也应该在解决方案中起作用。
【问题讨论】:
-
你可以用
set代替tuple -
@Ni。
frozenset、sets 不可散列,因此不能作为键 -
对,好点。
标签: python sorting dictionary tuples