python - 无法将代码更改为列表理解

标签 python matrix list-comprehension slice

我的问题有点简单,但我似乎找不到答案。

我的代码中有以下行可以正常工作:

Uniquesample = np.matrix([[   1.   ,    0.   ],
                   [   2.   , -106.965],
                   [   3.   ,  -83.835],
                   [   4.   ,   12.5  ],
                   [   5.   , -141.6  ],
                   [   6.   ,  -17.25 ],
                   [   7.   ,  -94.785],
                   [   8.   ,  -26.785],
                   [   9.   , -125.835],
                   [  10.   ,    6.865],
                   [  11.   ,   16.23 ],
                   [  12.   ,   61.45 ],
                   [  13.   ,   42.625],
                   [  14.   , -163.655],
                   [  15.   , -116.3  ],
                   [  16.   ,   15.82 ],
                   [  17.   , -166.055],
                   [  18.   ,   90.025],
                   [  19.   ,   14.215],
                   [  20.   ,   82.465]])
L, W = Uniquesample.shape
ModelNumber = 8
Members = np.zeros((L,ModelNumber*W))

seq=[4, 7, 9, 2, 15, 16, 19]
i=0
Count = [7]
for j in seq:
    Members[:Count[i]:,W*i:W*(i+1)] = Uniquesample[j]

Ps:Uniquesample 是一个 800 x 2 矩阵,因此为了简单起见,我只将前 20 行放在这里。 我尝试使用“列表理解”将 for 循环更改为另一种格式:

Members[:Count[i]:,W*i:W*(i+1)] = [Uniquesample[j] for j in seq]

但是它不起作用。我收到以下错误:“ValueError:使用序列设置数组元素。请求的数组将超过最大维数 2。”

事情是这样的。我是否将代码正确“翻译”为列表理解格式?

非常感谢

最佳答案

我在下面的示例中使用了 seq=[4, 7, 9, 2, 15, 16, 19]。初始的 Members 数组如下所示: enter image description here

在 for 循环中,Members[:Count[i]:,W*i:W*(i+1)] = Uniquesample[j] 将替换那些 7x2 元素(红色) 与 for 循环中的最终值。

enter image description here

但是列表理解 Members[:Count[i]:,W*i:W*(i+1)] = [Uniquesample[j] for j in seq] 将分配每个元素不同。

enter image description here

仅供引用,我使用的是 numpy 版本“1.18.5”,因此由于旧的 numpy 版本,它可能无法在 www.onlinegdb.com 上正常运行。

enter image description here

关于python - 无法将代码更改为列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67855468/

相关文章:

python /Javascript : WYSIWYG html editor - Handle large documents fast and/or design theory

python - Django createsuperuser 抛出 django.core.exceptions.FieldDoesNotExist : User has no field named ' ' error

python - 使用 numpy 元组中的值创建矩阵

matlab - 如何从现有矩阵中提取新矩阵

Python - 如何找到两个向量之间的相关性?

python - 如何使其成为列表理解

python - 将本地分支推送到远程分支

python - Python 中的 4x4 矩阵

python - 如何从字典中提取值并从中创建列表

python - 从 Pandas 数据框中去除 NaT 值