【问题标题】:TypeError: '<' not supported between instances of 'dict' and 'dict': Python 3 Conversion?TypeError:'dict'和'dict'的实例之间不支持'<':Python 3 Conversion?
【发布时间】:2020-02-03 03:00:05
【问题描述】:

我知道我正在使用 python 2 中的代码,而这些代码在 python 3 中不再适用。但是,我不确定如何调整我的代码,并且我目前无法运行 python 2。感谢任何见解。

我已经查看了这些现有线程,但我根本不明白如何将所学知识应用到我自己的用例中: TypeError: '<' not supported between instances of 'dict' and 'dict'
TypeError: '>' not supported between instances of 'dict' and 'dict'

我的代码

nodes=random.randint(47,52)
p=random.uniform(0.05,0.08)
name="Erdos-Renyi random weighted graph"
G=nx.erdos_renyi_graph(nodes,p)
maxw=random.randint(7,12)
weight=weight_attr(G,maxw)
w_edges=[(x,y,z) for (x,y),z in weight.items()]
G.add_weighted_edges_from(w_edges)
G=nx.Graph(G,name=name)
print ("Graph G is a %s with %i nodes, p=%.3f and %i edges\n" %(str(G),len(G.nodes()),p,len(G.edges())))

res = list(sorted(Counter(G.edges()), key=Counter(G.edges()).__getitem__, reverse=True))
for i in res:
    print ("Edge", i, "has weight", Counter(G.edges())[i]['weight'])

代码在这一行抛出错误:

res = list(sorted(Counter(G.edges()), key=Counter(G.edges()).__getitem__, reverse=True))
TypeError: '<' not supported between instances of 'dict' and 'dict'

【问题讨论】:

  • 代码应该做什么?也许有不同的方式?
  • 例如,您不必要地制作(至少}三个相同计数器的副本
  • @cricket_007 我的代码的第一部分工作正常 - 我正在计算加权图的节点和边。代码的第二部分是尝试计算我的图中每条边的权重。
  • 但是当G.edges() 可能已经是一个列表时,为什么还需要一个列表呢?

标签: python python-3.x sorting networkx


【解决方案1】:

虽然我不知道 NetworkX,但我认为不需要对任何内容进行排序或列出列表,因为您只是在打印内容

这应该可以帮助您调试代码,至少并且可能以不同的顺序打印类似的东西

edge_counter = Counter(G.edges())

for k, v in edge_counter.items():
    print(f'edge {k} has value {v}')

【讨论】:

    猜你喜欢
    • 2019-09-05
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    相关资源
    最近更新 更多