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行的函数不能对浮点数进行排序,但不知到怎么改