Ошибка типа:> не поддерживается между экземплярами dict и dict - PullRequest
0 голосов
/ 05 июня 2019

Я работаю со словарями, и у меня появляется следующая ошибка

'>' 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'

1 Ответ

0 голосов
/ 05 июня 2019

В 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

...