如何用Python for循环生成主对角线为0的multidict?
No problem, let's tweak your code to get exactly what you need! The issue with your current loop is that it generates random numbers for every (i,j) pair—including when i equals j. We just need to add a simple condition to handle that special case.
Step-by-Step Fix:
First, make sure you’ve imported the
randommodule at the top of your script:import random # If you're using the ortools multidict (as in your example), add this too: # from ortools.graph import pywrapgraph as pgModify your nested loops to check if
iandjare equal. If they match, set the value to 0; otherwise, generate a random integer between 1 and 101:N = 3 # Replace with your desired grid size arcs = {} for i in range(N): for j in range(N): if i == j: arcs[(i, j)] = 0 else: arcs[(i, j)] = random.randint(1, 101)Finally, pass this dictionary to
multidictjust like your example:# Using ortools' multidict (adjust if you're using a different implementation) arcs, capacity = pg.multidict(arcs)
Example Output (for N=3):
Running this code might produce a result that looks exactly like your sample:
# arcs holds all coordinate pairs, capacity holds their corresponding values {(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)} [0, 80, 11, 15, 0, 120, 103, 3, 0]
This ensures every coordinate pair where i=j gets a 0, while all other pairs get a random integer in your specified range.
内容的提问来源于stack exchange,提问作者user9158974

