反向访问numpy数组的Pythonic方法

2024-10-05 11:08:25 发布

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

我正在尝试重新编写一些看起来像是由FORTRAN程序员编写的代码,以使其更具Pythonic/可读性。下面是感兴趣的代码片段。代码的总体行为是,只要值小于1,就将Z的前三个元素存储到Zstart中;只要值小于1,就将Z的后三个值存储到Zend中。你知道吗

import numpy as np
nbpoints = 3
Z = np.linspace(0,1.0,10)
Zstart = np.ones(nbpoints)
Zend = np.ones(nbpoints)
Zpts = np.size(Z)
for j in range(nbpoints):
    if Z[j] < Zstart[j]:
       Zstart[j] = Z[j]
    if Z[Zpts - 1 - j] < Zend[nbpoints - 1 - j]:
        Zend[nbpoints - 1 - j] = Z[Zpts - 1 - j]

Zstart和Zend的反向移动访问从两端都有点绊倒了我。我目前的解决方案如下。你知道吗

import numpy as np
nbpoints = 3
Z = np.linspace(0,1.0,10)
Zstart = np.ones(nbpoints)
Zend = np.ones(nbpoints)
Zpts = np.size(Z)
for j in range(nbpoints):
    if Z[j] < Zstart[j]:
       Zstart[j] = Z[j]
    if Z[-(j+1)] < Zend[-(j+1)]:
        Zend[-(j+1)] = Z[-(j+1)]

此代码的示例输出为:

Z = [ 0.0 0.11111111  0.22222222  0.33333333  0.44444444  0.55555556 
0.66666667  0.77777778  0.88888889  1.0 ]

Zstart = [ 0.0 0.11111111  0.22222222]
Zend = [ 0.77777778  0.88888889  1.0 ]

我的解决方案让人觉得我还是在重新编写写得不好的代码,比如在泰坦尼克号甲板上重新摆放椅子。有没有一种更适合做这个手术的方法?你知道吗


Tags: 代码inimportnumpyforsizeifas
2条回答

此代码在没有移动计数器的情况下给出相同的结果

nbpoints = 3
Z=np.linspace(0,1.,10.)               
Zstart = np.ones(nbpoints)            
Zend = np.ones(nbpoints)              

Zstart[Z[:nbpoints] < 1] = Z[:nbpoints][Z[:nbpoints] < 1]  
Zend[Z[-nbpoints:] < 1] = Z[-nbpoints:][Z[-nbpoints:] < 1] 

不需要用np.ones实例化ZstartZend。直接构建它们:

nbpoints = 3
Z = np.linspace(0,1.0,10)
Zstart = Z[:nbpoints][Z[:nbpoints] < 1]
Zend = Z[-nbpoints:][Z[-nbpoints:] < 1]

print(Zstart)
print(Zend)
# [ 0.          0.11111111  0.22222222]    
# [ 0.77777778  0.88888889]

注意,Zend这里只有2个元素,因为Z中的最后一个元素不小于1。你知道吗

相关问题 更多 >

    热门问题