在字典中交换键和值的操作未正常工作。

huangapple go评论68阅读模式
英文:

switching key and values for values and keys in dictionary doesn't work properly

问题

我正在尝试计算具有不同邻居数量的节点出现次数,从一个边列表中获取,这在切换键和值时出现问题,元素会丢失,尽管在其他列表上运行正常,但在这个列表上它没有给出完整的输出。缺少什么?

[(0, 4), (1, 4), (2, 0), (3, 2), (4, 3)]
{0: 2, 4: 3, 1: 1, 2: 2, 3: 2}
Counter({2: 3, 3: 1, 1: 1})
{3: 2, 1: 1}  # 这里是错误的

count_occurances = Counter(occurances.values())
f = dict((v, k) for k, v in count_occurances.items())

期望的输出是
{3: 2, 1: 3}

英文:

I'm trying to count the occurances for nodes with number of neighbors from an edge list which is working except when I want to switch between keys and values, elements get lost, although it's working on other lists but this one it's not giving the entire output. what's missing?

[(0, 4), (1, 4), (2, 0), (3, 2), (4, 3)]
{0: 2, 4: 3, 1: 1, 2: 2, 3: 2}
Counter({2: 3, 3: 1, 1: 1})
{3: 2, 1: 1}  # here is wrong

 count_occurances = Counter(occurances.values())
 f = dict((v, k) for k, v in count_occurances.items())


the expected output is 
{3: 2, 1:3, 1: 1}

答案1

得分: 1

The Counter构造函数没有错。当你给它一个具有items方法的参数时,它会直接将其转换为键:计数对(字典不进行总计操作):

D = {2: 3, 3: 1, 1: 1} 
C = Counter(D)  

# C --> Counter({2: 3, 3: 1, 1: 1})

要颠倒计数器的值和键,你需要使用列表作为值,以便重复计数可以存储它们的所有键。

R = dict()
R.update((count, R.get(count, []) + [key]) for key, count in C.items())

# R --> {3: [2], 1: [3, 1]}
英文:

The Counter constructor is not wrong. When you give it a parameter that has an items method, it converts it directly to the key:count pairs (no totalling operation occurs for a dictionary):

D = {2: 3, 3: 1, 1: 1} 
C = Counter(D)  

# C --> Counter({2: 3, 3: 1, 1: 1})

To reverse the counter's values and keys, you'll need to use lists as values so that duplicate counts can store all of their keys.

R = dict()
R.update( (count,R.get(count,[])+[key]) for key,count in C.items() )

# R --> {3: [2], 1: [3, 1]}

huangapple
  • 本文由 发表于 2023年2月27日 08:09:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575810.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定