如果我正在编写C ++,则可以执行以下操作:
double foo [9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
double* bar = foo;
cout << bar[0] << ", " << bar[1] << ", " << bar[2] << "\n";
bar += 3;
cout << bar[0] << ", " << bar[1] << ", " << bar[2] << "\n";
bar += 3;
cout << bar[0] << ", " << bar[1] << ", " << bar[2] << "\n";
这将打印:
0, 1, 2
3, 4, 5
6, 7, 8
我现在想在numpy中做同样的事情:
foo = np.arange((9))
bar = foo[:3]
print(bar)
???
print(bar)
???
print(bar)
但是我不知道要放在???
上是什么,结果希望是:
[0 1 2]
[3 4 5]
[6 7 8]
换句话说,我正在寻找一种使用现有引用bar
来更改视图foo
指向bar
的位置的方法。
那是我希望能够将???
编写为bar = f(bar)
,其中f
是用户定义的某些功能。
编辑:
这是我目前的做法:
def f(idx=[0]): #mutable default argument
idx[0] += 3
return foo[idx[0]-3:idx[0]]
for key in key_list:
a_dict[key] = f()
b_dict[key] = f()
for view in range(num_views):
a_list.append(f())
b_list.append(f())
它必须在向量中,因为scipy.optimize.least_squares
需要将所有值存储在同一向量中。
答案 0 :(得分:1)
pythonic方法是使用indeces:
foo = np.arange(9)
bar = np.arange(3)
print(foo[bar])
>> array([0, 1, 2])
bar += 3
print(foo[bar])
>> array([3, 4, 5])
bar += 3
print(foo[bar])
>> array([6, 7, 8])
较少使用python方式(但与您编写的代码更相似)是使用迭代器:
foo = np.arange(9)
bar = foo.reshape(3,3).__iter__() # or use bar = iter(foo.reshape(3,3))
bar.__next__() # or use next(bar)
>> array([0, 1, 2])
bar.__next__()
>> array([3, 4, 5])
bar.__next__()
>> array([6, 7, 8])
答案 1 :(得分:0)
gdbserver
答案 2 :(得分:0)
foo = np.arange((9))
loopcounter = 3
startindex = 0
stopindex = startindex + loopcounter
print(foo[startindex:stopindex])
startindex = stopindex
stopindex = startindex + loopcounter
print(foo[startindex:stopindex])
startindex = stopindex
stopindex = startindex + loopcounter
print(foo[startindex:stopindex])
...