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

Python生成二维随机数组报错IndexError: List index out of range求助

Fixing the IndexError in Your 2D Random Array Code

Hey there! Let's break down why you're hitting that IndexError: List index out of range and fix it up.

The Root Cause

You initialized Prob as a list of empty lists with Prob=[[] for x in xrange(n)]. When you try to run Prob[i][j].append(random()), here's what's going wrong:

  • Prob[i] is an empty list at the start of each outer loop iteration
  • There is no j-th element in that empty list yet, so accessing Prob[i][j] throws an index out of range error immediately.

Fixed Code Option 1: Iterative Appending

Instead of trying to index into the inner list before it has elements, just append directly to Prob[i]:

from random import random
n = 10
t = 5
Prob = [[] for x in range(n)]  # Use range() instead of xrange() for Python 3 compatibility
for i in range(n):
    for j in range(t):
        Prob[i].append(random())  # Append directly to the inner list
print(Prob)
print(Prob[1][1])

Fixed Code Option 2: Nested List Comprehension (Cleaner & More Efficient)

For a more concise approach, use a nested list comprehension to generate the 2D array in one line:

from random import random
n = 10
t = 5
Prob = [[random() for _ in range(t)] for _ in range(n)]
print(Prob)
print(Prob[1][1])

Both versions will correctly generate a 10x5 2D list of random floats, and Prob[1][1] will return the second element of the second inner list without any errors.

内容的提问来源于stack exchange,提问作者OB1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 09:37:51