# 函数返回带有networkx元素的列表Function returning a list with networkx elements

``````# function to generate a sequence of barabasi-albert random graphs
import networkx as nx

def pa_graph_seq(n, m, c=0, G=None, seed=None, seq=True):

# Note: seq = True means function returns a list of
#       networkx graph objects. Otherwise returns the
#       graph from the final time slice

# Some preliminary checks
if m<1 or m>=n:
raise nx.NetworkXError(\
"BA network must have m>=1 and m<n, m=%d,n=%d"%(m,n))
if seed is not None:
random.seed(seed)
if G is not None and len(G) >= n:
raise nx.NetworkXError(\
"G must have strictly less than n nodes")

# If initial graph was not specified, initialize empty graph
if G==None: G = nx.MultiGraph()

# If seq==True, initialize the list with the initial graph
if seq==True: Gseq = [G]

# Grow the graph
step = len(G)+1
while step <= n:
# Add a single node

for i in range(m):
# Get degree sequence of current graph
deg = nx.degree(G)
d = deg.values()

# Increment degree of new node by 1
d[len(d)-1] = d[len(d)-1]+1

# Sample node and attach edge
newnode = deg_sample(d,c)

# If seq==True, append onto Gseq
if seq==True: Gseq.append(G)

step += 1

# Next loop for debugging only
for i in range(len(Gseq)):
print nx.nodes(Gseq[i])

if seq == True:
return Gseq
else:
return G
``````

`Gseq`的奇怪问题是，最终的`Gseq`列表似乎只包含最终图形的`n`副本。 例如，小型调试循环（ `# Next loop for...` ）中的输出如下所示：

``````[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
``````

## 1 个回复1

### ===============>>#1 票数：1 已采纳

``````if seq==True: Gseq.append(G.copy())
``````