Python - 将二维数组中的列设置为特定值的最佳方法

mik*_*kip 9 python multidimensional-array

我有一个2d数组,我想设置一个特定值的列,我的代码如下.这是python的最佳方式吗?

rows = 5
cols = 10

data = (rows * cols) *[0]
val = 10
set_col = 5

for row in range(rows):
    data[row * cols + set_col - 1] = val
Run Code Online (Sandbox Code Playgroud)

如果我想将一些列设置为特定值,我该如何扩展它

我想只使用python标准库

谢谢

jfs*_*jfs 27

NumPy包提供强大的N维数组对象.如果datanumpy数组,则将set_col列设置为valvalue:

data[:, set_col] = val
Run Code Online (Sandbox Code Playgroud)

完整示例:

>>> import numpy as np
>>> a = np.arange(10)
>>> a.shape = (5,2)
>>> a
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])
>>> a[:,1] = -1
>>> a
array([[ 0, -1],
       [ 2, -1],
       [ 4, -1],
       [ 6, -1],
       [ 8, -1]])
Run Code Online (Sandbox Code Playgroud)


Max*_*keh 14

更好的解决方案是:

data = [[0] * cols for i in range(rows)]
Run Code Online (Sandbox Code Playgroud)

对于价值cols = 2,rows = 3我们得到:

data = [[0, 0],
        [0, 0],
        [0, 0]]
Run Code Online (Sandbox Code Playgroud)

然后你可以访问它:

v = data[row][col]
Run Code Online (Sandbox Code Playgroud)

这导致:

val = 10
set_col = 5

for row in range(rows):
    data[row][set_col] = val
Run Code Online (Sandbox Code Playgroud)

或者更多的Pythonic(感谢JF Sebastian):

for row in data:
    row[set_col] = val
Run Code Online (Sandbox Code Playgroud)

  • 不需要使用显式行索引:`for data in data:\n row [col_index] = value` (5认同)