gpt4 book ai didi

python - 如何根据数组中的条件在 python 中复制数组?

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:53 25 4
gpt4 key购买 nike

我有一个

n = np.array([[1, 12, 1, 3],
[1, 1, 12, 0]])

并且想复制它,这样如果我在数组中有一个两位数,它会将数组分成两个相同的数组,其中第一个数组具有第一个数字,第二个数组具有第二个数字。在上面的例子中,我有 4 个矩阵副本。假设数组中有一位数或两位数。

n1 = [1, 1, 1, 3], [1, 1, 1, 0]
n2 = [1, 1, 1, 3], [1, 1, 2, 0]
n3 = [1, 2, 1, 3], [1, 1, 1, 0]
n4 = [1, 2, 1, 3], [1, 1, 2, 0]

最佳答案

方法 1:itertools.product

>>> import numpy as np
>>> from itertools import product
>>> from pprint import pprint
>>>
>>> n = np.array([[1, 12, 1, 3],
... [1, 1, 12, 0]])
>>>
>>> pprint([np.reshape(nn, n.shape).astype(int) for nn in product(*map(str, n.ravel()))])
[array([[1, 1, 1, 3],
[1, 1, 1, 0]]),
array([[1, 1, 1, 3],
[1, 1, 2, 0]]),
array([[1, 2, 1, 3],
[1, 1, 1, 0]]),
array([[1, 2, 1, 3],
[1, 1, 2, 0]])]

请注意,这也适用于较长的数字。

>>> n = np.array([462, 3, 15, 1, 0])
>>> pprint([np.reshape(nn, n.shape).astype(int) for nn in product(*map(str, n.ravel()))])
[array([4, 3, 1, 1, 0]),
array([4, 3, 5, 1, 0]),
array([6, 3, 1, 1, 0]),
array([6, 3, 5, 1, 0]),
array([2, 3, 1, 1, 0]),
array([2, 3, 5, 1, 0])]

方法 2:np.meshgrid

>>> import numpy as np
>>>
>>> n = np.array([[1, 12, 1, 3],
... [1, 1, 12, 0]])
>>>
>>> te = np.where(n>=10)
>>> dims = tuple(np.log10(n[te]).astype(int) + 1)
>>>
>>> out = np.empty(dims + n.shape, dtype=n.dtype)
>>> out[...] = n
>>> out[(Ellipsis,) + te] = np.moveaxis(np.meshgrid(*(s//10**np.arange(i)[::-1]%10 for i, s in zip(dims, n[te])), indexing='ij'), 0, -1)
>>>
>>> out
array([[[[1, 1, 1, 3],
[1, 1, 1, 0]],

[[1, 1, 1, 3],
[1, 1, 2, 0]]],


[[[1, 2, 1, 3],
[1, 1, 1, 0]],

[[1, 2, 1, 3],
[1, 1, 2, 0]]]])

关于python - 如何根据数组中的条件在 python 中复制数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48505801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com