如何填写空数组无效语法

2024-06-26 10:19:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个要填充的空数组。你知道吗

数组是10乘10。我希望第一行和第一列显示文本名称,我在一个9的列表中。我希望内部的9乘9单元格包含另一个矩阵,我已经用值填充了这个矩阵。你知道吗

以下是我如何制作矩阵并尝试填写到目前为止的名称:

rows, cols = (10, 10)
array = [[0 for i in range (cols)] for j in range (rows)]
array [0][1:9] = photographs
array [1:9][0] = photographs

其中photographs是我的9个单词列表。你知道吗

这提供了一个数组,其中第一行是所需的,但第一列仍然显示0。你知道吗

这就是我的数组的样子:

[[0, 'DSC001 \n', 'DSC4587 \n', 'DSC3948 \n', 'DSC98798 \n', 'DSC44 \n', 'DSC098098d \n', 'DSC098734a-796876 \n', 'DSC8976 \n', 'DSC098707-a-b \n', 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

我试图使第一行和第一列中的单元格显示-或仅显示一个空格,但返回了以下错误:

    array [0][0] = -
                   ^
SyntaxError: invalid syntax

我还尝试用9乘9矩阵中的值填充数组,如下所示:

array [1:9][1:9] = matrix

但这根本不起作用。你知道吗


Tags: in文本名称列表forrange矩阵数组
2条回答
nrows = 4
ncols = 4

# Initialize an empty list of lists.
# NB this is a list of lists, not an array. Think of the outer list as a list of rows. Each row is an inner list of 1 element per column.
array = [[0] * ncols for _ in range(ncols)]

# Note that array[n] gets the nth row. array[n][m] gets the element at (n, m).   
# But to get the mth column, you need to do [array[row][m] for row in range(nrows)]. 
# This is reason enough to start thinking about numpy or pandas for an application list this.

headers = ["A", "B", "C"]

# Add the row headers to your 'array'
array[0][1:] = headers
# remember that array[0] gets the first row. It is a list. You can get all the elements except the first by slicing it with [1:]

# Add the column headers to your 'array'
for row_number, row in enumerate(array[1:]):
    row[0] = headers[row_number]
# in this case we need a loop as we want to change the first element of each of the inner lists. A loop over array gives us a row at each iteration. row[0] is then the first column of that row.

# put - in the corner
array[0][0] = "-"

# fill the array with another list

data = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]
# because both data and array are lists of rows, we do this row by row, skipping the first row
for data_row_number, array_row in enumerate(array[1:]):
    array_row[1:] = data[data_row_number]

给出的array的输出

[['-', 'A', 'B', 'C'], ['A', 1, 2, 3], ['B', 4, 5, 6], ['C', 7, 8, 9]]

填写第一栏应

array[0][1:10] = photographs

在python中,列表片段从起始数字到比结束数字小一个,就像range

不能使用array[1:9][0]引用第一列。 array[1:9]是一个包含索引为1到8的行的列表(所以第2行到第9行),所以array[1:9][0]只是第二行。可以使用for循环插入列名,例如:

for row in array[1:10]:
    row[0] = photographs[i]

另外,要在所需的第一个单元格中插入值:

array[0][0] = '-'

就像分配变量一样。你知道吗

相关问题 更多 >