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 accessingProb[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
相关产品推荐
相关产品推荐

