如何高效生成从0开始连续取值的矩阵?以4*4(0到16)及10*10(0到100)矩阵为例
Hey there! Generating matrices with consecutive values starting from 0 doesn’t require typing out every single number—let’s break down the easiest, most scalable ways to make your 4x4 and 10x10 grids.
Option 1: Use NumPy (Best for Speed & Large Matrices)
NumPy is built for this kind of numerical work—it’s fast, clean, and perfect for any size matrix. Here’s how to use it:
4x4 Matrix (0 to 15, since 4×4 = 16 elements)
If you meant a full 4x4 grid with values from 0 to 15 (the standard sequential fill), run this:
import numpy as np # Create a flat array of 0-15, then reshape into 4 rows and 4 columns four_by_four = np.arange(16).reshape(4, 4) print(four_by_four)
Output:
[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]]
Note: If you truly need values up to 16 (17 total), you can’t make a perfect 4x4 square—you’d need a 4x5 matrix instead with np.arange(17).reshape(4, 5).
10x10 Matrix (0 to 99, 10×10 = 100 elements)
For a 10x10 grid, the logic is identical—just adjust the numbers:
ten_by_ten = np.arange(100).reshape(10, 10) print(ten_by_ten)
This will give you a grid where each row starts 10 higher than the last, with values running 0 to 99 in order.
Option 2: Pure Python (No External Libraries)
If you can’t install NumPy, list comprehensions are a great alternative—still way better than manual entry:
4x4 Matrix
# For each row i, calculate the starting value (i*4) and add 0-3 to fill the row four_by_four = [[i * 4 + j for j in range(4)] for i in range(4)] print(four_by_four)
10x10 Matrix
Same idea, scaled to 10 columns/rows:
ten_by_ten = [[i * 10 + j for j in range(10)] for i in range(10)] print(ten_by_ten)
Why This Is Way Better Than Manual Building
- Scalable: Need a 20x20 matrix? Just change the numbers in two spots instead of rewriting 400 values.
- Error-proof: No typos from typing every number by hand.
- Flexible: Want to start at 1 instead of 0? Just adjust the code—for NumPy, use
np.arange(1, 17); for pure Python, add+1to the inner expression.
内容的提问来源于stack exchange,提问作者awannabecs

