小编Mon*_*e27的帖子

为相同的字典值创建可交换元组键的最佳方法是什么?

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 元素可交换但也引用相同值的最佳方法是什么。

此外,字符串也应该在解决方案中起作用。

python sorting dictionary tuples

0
推荐指数
1
解决办法
631
查看次数

标签 统计

dictionary ×1

python ×1

sorting ×1

tuples ×1