You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python for循环生成主对角线为0的multidict?

Fixing Your Multidict Generation Code

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:

  1. First, make sure you’ve imported the random module 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 pg
    
  2. Modify your nested loops to check if i and j are 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)
    
  3. Finally, pass this dictionary to multidict just 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:49:38