nuan11111 2021-10-18 21:00 采纳率: 50%
浏览 113
已结题

python networkx 出现报错,但是不知道为什么

import networkx as nx
import random
import matplotlib.pyplot as plt

G = nx.Graph()
H = nx.path_graph(50)
G.add_nodes_from(H)

def rand_edge(vi,vj,p=0.2):
    probability =random.random()
    if(probability<p):
        G.add_edge(vi,vj)
i=0
while (i<50):
    j=0
    while(j<i):
            rand_edge(i,j)
            j +=1
    i +=1

number_components = nx.number_connected_components(G)
largest_components = max(nx.connected_components(G), key=len)
deg=nx.degree(G)
DVweight = G.degree()
degree_sum = sum(span for n, span in DVweight)         #各节点度数之和
degree_max = max(span for n, span in DVweight)        #节点最大度数

def sorted_map(map):
    ms = sorted(map, key = lambda element:(-element[1], element[0]))
    return ms

ds = sorted_map(deg)
c = ds[0:9]
print(c)

ci = nx.closeness_centrality(G)
cs = sorted_map(ci)
print(cs)

nx.draw_networkx(G, with_labels=True)
plt.show()

出现报错:'int' object is not subscriptable
感觉是第29行的代码出现问题,c的结果可以print出来,而cs却出现报错,个人猜测ci产生浮点数,29行的函数不能对浮点数进行排序,但不知到怎么改

  • 写回答

1条回答 默认 最新

  • 江天暮雪丨 2021-10-19 09:07
    关注
    ci = nx.closeness_centrality(G)
    cs = sorted_map(ci)
    print(cs)
    

    改为

    ci = nx.closeness_centrality(G)
    cs = sorted_map(ci.items())
    print(cs)
    

    解析:变量 ci 是一个字典,直接对它进行迭代,实际是所有键组成的序列,而这里需要的是对键值对进行迭代,因此使用 items() 方法将字典化为可迭代的键值对序列

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 10月27日
  • 已采纳回答 10月19日
  • 创建了问题 10月18日

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?