Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:为字典中的元组排列添加值并删除条目_Python_Algorithm_Dictionary_Permutation - Fatal编程技术网

Python:为字典中的元组排列添加值并删除条目

Python:为字典中的元组排列添加值并删除条目,python,algorithm,dictionary,permutation,Python,Algorithm,Dictionary,Permutation,我有一本关键是元组的字典。其中一些元组是彼此的排列(例如(1,2)与(2,1))。我想把一种排列的值加到另一种排列的值上,然后去掉第二种排列 d = {(1, 3): 14, (1, 4): 13, (1, 2): 10, (11, 11): 19, (3, 1): 50, (4, 1): 5, ...} 应该是 {(1, 3): 64, (1, 4): 18, (1, 2): 10, (11, 11): 19, ...} 我考虑过对它们进行排序,然后根据它们在字典中的位置做一些事情,但这并

我有一本关键是元组的字典。其中一些元组是彼此的排列(例如
(1,2)
(2,1)
)。我想把一种排列的值加到另一种排列的值上,然后去掉第二种排列

d = {(1, 3): 14, (1, 4): 13, (1, 2): 10, (11, 11): 19, (3, 1): 50, (4, 1): 5, ...}
应该是

{(1, 3): 64, (1, 4): 18, (1, 2): 10, (11, 11): 19, ...}

我考虑过对它们进行排序,然后根据它们在字典中的位置做一些事情,但这并不容易扩大。欢迎输入

使用dict键而不是元组。然后,您可以在进行时添加它们,而无需担心订购

正如@wim所建议的,您可能应该使用
冻结集
,然后您可以使用
集合。计数器
总和
将值累积到新字典中:

from collections import Counter

d = {(1, 3): 14, (1, 4): 13, (1, 2): 10, (11, 11): 19, (3, 1): 50, (4, 1): 5}

r = sum((Counter({frozenset(k): v}) for k, v in d.items()), Counter())
print(r)
# Counter({frozenset({1, 3}): 64, frozenset({11}): 19, frozenset({1, 4}): 18, frozenset({1, 2}): 10})
如果您希望使用字典理解,可以将
计数器
对象转换为普通dict,并将键返回元组