如何在Python中固定随机生成器?

2 投票
2 回答
1069 浏览
提问于 2025-04-16 21:25

我有一段代码,可以随机给我网络中的每个节点分配一个标签,要么是'up'(向上),要么是'down'(向下)。

我该怎么做才能让这些随机标签固定下来,以后每次运行代码时都不会改变呢?

import networkx
import random

def assign_nodes(G):
    state = ['up','down']
    for n in G:
        G.node[n]['sign']=random.choice(state)
if __name__ =='__main__':
    input_data = open("data_test.txt",'r')
    graph = read_graph(input_data)
    assign_nodes(graph)

2 个回答

0

你可以保存这个图表:

from random import random
import networkx as nx

def make_graph():
    G=nx.DiGraph()
    N=10
    #make a random graph
    for i in range(N):
        for j in range(i):
            if 4*random()<1:
                G.add_edge(i,j)

    nx.write_dot(G,"savedgraph.dot")
    return G

try:
    G=nx.read_dot("savedgraph.dot")
except:
    G=make_graph() #This will fail if you don't use the same seed but have created the graph in the past. You could use the Singleton design pattern here.
print G.adj
7

使用 random.seed(常量) 来设置随机数生成器的初始值为一个固定的数字(把 常量 替换成你想要的数字)。

撰写回答