我正在尝试重新编写一些看起来像是由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 ]
我的解决方案让人觉得我还是在重新编写写得不好的代码,比如在泰坦尼克号甲板上重新摆放椅子。有没有一种更适合做这个手术的方法?你知道吗
此代码在没有移动计数器的情况下给出相同的结果
不需要用
np.ones
实例化Zstart
和Zend
。直接构建它们:注意,
Zend
这里只有2个元素,因为Z
中的最后一个元素不小于1。你知道吗相关问题 更多 >
编程相关推荐