我正在使用字典,但出现以下错误
'>' not supported between instances of 'dict' and 'dict'
我知道Python 2.7和3.x版本的字典存在一些问题。
print("number of nodes %d" % G.number_of_nodes())
print("number of edges %d" % G.number_of_edges())
print("Graph is connected?: %s" % nx.is_connected(G))
print("Number of connected components: %s" % nx.number_connected_components(G))
print("Size of connected componnents: %s" % [len(cc) for cc in nx.connected_components(G)])
print("Network Analysis will be performed on the largest cc from now on")
largest_cc = max(nx.connected_component_subgraphs(G), key=len)
dict_communities={}
num_communities=max([y for x,y in largest_cc.nodes(data=True)]).values()[0]
for i in range (1,num_communities+1):
dict_communities[i] = [x for x,y in largest_cc.nodes(data=True) if y['community']==i]
TypeError Traceback (most recent call last)
<ipython-input-12-fd6e5cb0ddb5> in <module>
1 dict_communities={}
----> 2 num_communities=max([y for x,y in largest_cc.nodes(data=True)])[0]
3 for i in range (1,num_communities+1):
4 dict_communities[i] = [x for x,y in largest_cc.nodes(data=True) if y['community']==i]
TypeError: '>' not supported between instances of 'dict' and 'dict'
答案 0 :(得分:0)
在networkx中,graph.nodes(data=True)
返回带有节点参数的node_id-dicts元组的列表。但是在Python中,字典无法比较(调用max
函数时您试图比较它们)。您应该使用另一种方式来完成此操作,例如使用如下代码提取每个节点的特定参数:
max([y['some_argument'] for x,y in largest_cc.nodes(data=True)])
^
|
Add it ----+
这里是示例:
我们创建一个随机图,并在参数'arg'中填充随机数:
import networkx as nx
import random
G = nx.gnp_random_graph(10,0.3,directed=True)
for node in G.nodes:
G.nodes[node]['arg'] = random.randint(1, 10)
然后,我们尝试使用您的代码:
[y for x,y in G.nodes(data=True)]
它返回:
[{'arg': 8}, {'arg': 5}, {'arg': 9}, {'arg': 4}, {'arg': 8}, {'arg': 6}, {'arg': 3}, {'arg': 2}, {'arg': 8}, {'arg': 1}]
而且您无法将这些字典相互比较。
但是如果您要在列表中指定“ arg”:
[y['arg'] for x,y in G.nodes(data=True)]
它将返回:
[8, 1, 5, 3, 10, 5, 7, 10, 1, 2]
您可以选择最大的元素(但不要在行尾写.values()[0]
,这会导致错误):
max([y['arg'] for x,y in G.nodes(data=True)])
10