用类实例替换数组中的元素

2024-04-19 00:08:41 发布

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

这与this相似,所以请先阅读它以了解我要做什么。在

现在,我想在上课的时候更换实例。什么比如:

import numpy as np

class B():
    def __init__(self, a,b):
        self.a = a
        self.b = b


arr = np.array([ [1,2,3,4,5],[6,7,8,9,10] ])

b1 = np.array([B(100,'a'),
               B(11,'b'),
               B(300,'c'),
               B(33,'d')])

b2 = np.array([B(45,'a'),
              B(65,'b'),
              B(77,'c'),
              B(88,'d')])

# My d array will be like that and I will have to 
# run 3 loops as below . I can't change that
d = np.array([[b1],[b2]],dtype=object)

# Replace the elements
for i in d:
    for y in i:
        for idx,el in enumerate(y): 
            #y[idx].a = arr.reshape(-1,5) # 5 is the size of every sublength of arr
            #print(y[idx].a)
            pass

# Show the updated values
for i in d:       
    for y in i:
        for idx,x in enumerate(y):
            print(y[idx].a)

我不能使用b = arr.reshape(-1, a.size),因为它必须运行在循环。但是,正如我所说的,b数组将是y[idx].value,所以我不能仅仅把它放在第3个循环中,因为我将获得错误的结果,也不能将它放在第3个循环之外,因为我无法访问类实例的value部分。在

我希望我的结果是:

^{pr2}$

因此,我只想填充a部分,例如B类实例。 注意,和前面的问题一样,B被展开以容纳arr中的所有5个值。在

简而言之,检查arr的每个子列表的长度(现在是5), 并更新d值相应的。所以,如果b1b2有4个值,则它们必须变成5个值(前5个值来自arr,后5个值来自arr)。在


Tags: the实例inselfforthatasnp
2条回答

这样做替换块。另外请注意,这假设您的arr将严格地以5的倍数表示,并且arr中的块将与示例中给定的一样多,如b1、b2等。在

for i,b_arr in enumerate(d):
    temp_arr = []
    for j in range(5):
        if j<len(b_arr)
            temp_arr.append(B(arr[i,j],b_arr[j].b))
        else:
            temp_arr.append(B(arr[i,j],b_arr[-1].b))
     d[i] = np.array(temp_arr) ## not sure if this step is right, not too familiar with numpy.

所以我补充说

print(d.shape)
print(d)

然后得到

^{pr2}$

__repr__添加到B我得到

1231:~/mypy$ python3 stack42283851.py 
(2, 1, 4)
[[[B(100, a) B(11, b) B(300, c) B(33, d)]]

 [[B(45, a) B(65, b) B(77, c) B(88, d)]]]

添加

import itertools
for a,b in itertools.zip_longest(arr[0,:],b1):
     print(a,b)

生产

1 B(100, a)
2 B(11, b)
3 B(300, c)
4 B(33, d)
5 None

将其改为:

newlist = []
for a,b in itertools.zip_longest(arr[0,:],b1):
    if b is not None:
        new_b = B(a, b.b)
        last_b = b
    else:
        new_b = B(a, last_b.b)
    newlist.append(new_b)
print(np.array(newlist))

生产

[B(1, a) B(2, b) B(3, c) B(4, d) B(5, d)]

将其赋给b1,并对a[1,:]b2重复上述操作。在

为了更简洁一点,我可以将new_b代码编写为函数,并将循环重写为列表理解。在

是的,我可以在适当的地方修改b,例如

b.a = a

但是既然我需要创建一个新的B对象来替换None,那又何必费心呢。我无法将新的B对象添加到原始的b1数组中。因此,通过列表创建新数组更简单。在


我可以对d和{}进行就地更改:

def replace(a,b):
    b.a = a
f = np.frompyfunc(replace, 2, 1)
f(arr[:,None,:4], d)      # produces array of None; ignore
print(d)
print(b1)

[[[B(1, a) B(2, b) B(3, c) B(4, d)]]  # chgd d

[[B(6, a) B(7, b) B(8, c) B(9, d)]]]
[B(1, a) B(2, b) B(3, c) B(4, d)]    # chgd b1

我只是用frompyfunc作为一种懒人的广播方式arrd进行迭代。请注意,我必须更改arr以匹配d形状。{cd19>也不会添加这个。显然你不能在原地做。在


我的B

class B():
    def __init__(self, a,b):
        self.a = a
        self.b = b
    def __repr__(self):
        return 'B(%s, %s)'%(self.a, self.b)

frompyfunc更多:

getB_b = np.frompyfunc(lambda x: x.b, 1,1)   # fetch b attributes
print(getB_b(d))
#[[['a' 'b' 'c' 'd']]
#
# [['a' 'b' 'c' 'd']]]

mkB = np.frompyfunc(B, 2,1)   # build array of B() with broadcasting
print(mkB(arr, ['a','b','c','d','e']))
# [[B(1, a) B(2, b) B(3, c) B(4, d) B(5, e)]
#  [B(6, a) B(7, b) B(8, c) B(9, d) B(10, e)]]

print(mkB(arr[:,:4], getB_b(d[:,0,:])))
# [[B(1, a) B(2, b) B(3, c) B(4, d)]
#  [B(6, a) B(7, b) B(8, c) B(9, d)]]

编辑评论

arr1 = np.array([ [1,2],[6,7] ])
newlist = []
for a,b in itertools.zip_longest(arr1[0,:],b1):
    if b is not None:
        new_b = B(a, b.b)
        last_b = b
    else:
        new_b = B(a, last_b.b)
    newlist.append(new_b)
print(np.array(newlist))

生产

[B(1, a) B(2, b) B(None, c) B(None, d)]

arr较短时,a将是{}(而不是{});因此我们需要对此进行测试

def foo(arr,bn):
    newlist = []
    for a,b in itertools.zip_longest(arr,bn):
        print(a,b)
        if a is None:
            pass
        else:
            if b is not None:
                new_b = B(a, b.b)
                last_b = b
            else:
                new_b = B(a, last_b.b)
            newlist.append(new_b)
    return newlist
print(np.array(foo(arr1[0,:],b1)))  # arr1 shorter
print(np.array(foo(arr[0,:], b2)))  # arr longer 

测试:

1 B(1, a)
2 B(2, b)
None B(3, c)
None B(4, d)
[B(1, a) B(2, b)]

1 B(6, a)
2 B(7, b)
3 B(8, c)
4 B(9, d)
5 None
[B(1, a) B(2, b) B(3, c) B(4, d) B(5, d)]

没有什么特别或神奇的东西,只是要确保我的if测试和缩进正确。在

相关问题 更多 >