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

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日