Warm tip: This article is reproduced from stackoverflow.com, please click

发布于 2020-04-10 16:05:49

I would like to create a matrix with cells that increment by 10. For example, the output of a 3x3 matrix should be:

`[[10, 20, 30], [40, 50, 60], [70, 80, 90]]`

The code I currently have creates a 3x3 matrix filled with 0s:

```
print([[0 for x in range(3)] for y in range(3)])
output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
```

Questioner

Newbie123

Viewed

69

Try this on for size

```
print([[30*y + 10*x for x in range(3)] for y in range(3)])
```

What this does is swaps out the `0`

you were using with `30*y + 10*x`

which is exactly what you need to generate your array. For a more general solution that lets you scale to n by n matrices you can use

```
n = k
print([[10*k*y + 10*x for x in range(k)] for y in range(k)])
```

For different rows and columns you can use

```
rows = k
cols = j
print([[10*cols*y + 10*x for x in range(cols)] for y in range(rows)])
```