所以我添加
print(d.shape)
print(d)
and get
2249:~/mypy$ python3 stack42283851.py
(2, 1, 4)
[[[<__main__.B object at 0xb71d760c> <__main__.B object at 0xb71d7aac>
<__main__.B object at 0xb71d7acc> <__main__.B object at 0xb71e5cec>]]
[[<__main__.B object at 0xb391718c> <__main__.B object at 0xb39171ac>
<__main__.B object at 0xb39171cc> <__main__.B object at 0xb39171ec>]]]
添加一个__repr__
to B
I get
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)]]]
Adding
import itertools
for a,b in itertools.zip_longest(arr[0,:],b1):
print(a,b)
produces
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))
produces
[B(1, a) B(2, b) B(3, c) B(4, d) B(5, d)]
将其分配给b1
,并重复a[1,:]
and b2
.
为了更干净一点,我可以这样写new_b
代码作为函数,并将循环重写为列表理解。
是的,我可以修改b
到位,例如
b.a = a
但因为我需要创建一个新的B
对象来替换None
, 何必。我无法添加新的B
反对原文b1
大批。所以通过列表创建新数组更简单。
我可以就地更改d
and b1
with:
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
作为一种懒人的广播方式arr
反对d
并迭代所有元素。请注意,我必须改变arr
匹配d
形状。而且这并没有添加任何新的B()
。显然你不能就地做到这一点。
My B
is
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))
produces
[B(1, a) B(2, b) B(None, c) B(None, d)]
When arr
较短,a
将None
(代替b
);所以我们需要测试一下
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
testing:
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
测试和缩进正确。