如何修复AttributeError: 'dict_values'对象没有属性'count'?

15

这是我的代码,文本文件在这里

import networkx as nx
import pylab as plt

webg = nx.read_edgelist('web-graph.txt',create_using=nx.DiGraph(),nodetype=int)
in_degrees = webg.in_degree()
in_values = sorted(set(in_degrees.values()))
in_hist = [in_degrees.values().count(x)for x in in_values]

我想绘制度分布网络图,如何将字典更改为可解决的形式?


1
我假设您正在使用Python 3。如果是这样,请在您的问题中添加python-3.x标签。一些dict方法在Python 3和Python 2中的行为不同。 - PM 2Ring
3个回答

19

在Python3中,dict.values()返回的是“视图”,而不是列表:

要将“视图”转换为列表,只需用 list()in_degrees.values() 包装起来即可:

in_hist = [list(in_degrees.values()).count(x) for x in in_values]

0

我只是使用了 list(in_degrees.values()).count(x),这对我很有效!


-1
如果你想计算字典的值,可以像这样做:
len(list(dict.values()))

对于键,同样的方法适用。

len(list(dict.keys()))

还要记住,如果你想把所有的键或值都放在列表里,只需使用list(dict.values())


1
在这种情况下,len(mydict)就足够了,因为字典的长度是指键的数量。不需要生成值或键列表。而且通过使用list操作符来制作副本也是不必要的,因为mydict.keys()mydict.values()都返回列表。 - Bonlenfum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接