【问题标题】:TypeError: '>' not supported between instances of 'dict' and 'dict'TypeError:'dict'和'dict'的实例之间不支持'>'
【发布时间】:2019-06-05 17:00:00
【问题描述】:

我正在使用字典,但出现以下错误

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

【问题讨论】:

  • 哪一行给出了这个错误?错误消息本身非常清楚,某处代码被要求比较两个字典,其中一个更大,这是没有意义的。 (通常这发生在某种类型的带有字典的排序调用中)。请问完整的回溯吗?
  • 您指的是什么“问题”? Python 3 不再像 Python 2 那样选择任意比较方法,而是不再允许 dict 比较。
  • 太棒了!但是我该如何解决呢?
  • try num_communities=max([y for x,y in largest_cc.nodes(data=True)], key=len).values()[0] 请注意,很难知道您要做什么,因为我们没有提供给我们的图表,此时这只是对您的猜测想要你的代码去做。

标签: python dictionary python-3.6 networkx


【解决方案1】:

在 networkx 中,graph.nodes(data=True) 返回带有节点参数的 node_id-dicts 元组列表。但是在 Python 中无法比较 dicts(当您调用 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

【讨论】:

    猜你喜欢
    • 2019-09-05
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 2020-09-07
    相关资源
    最近更新 更多