Converting Fortran 77 code to Python

时间:2017-12-18 08:34:31

标签: python fortran fortran77

I have looked at this Q/A Intent of this Fotran77 code and I have almost converted the below Fortran77 style code into Python 3.x except I had a doubt where the i = i + 1 should be placed in the Python version. As mentioned in the comments of the linked question I have done the conformance tests and the results are off by a margin of 2. Hence the question.

itemManager

Here is my Python version

i = 0
500 continue
i = i +1
if (i .le. ni) then
  if (u(i,j-1) .gt. -9999.) then
     r(1,j) = u(i,j-1)
     go to 600
  else
    missing = i
    go to 500
  end if
 end if
600  continue

Did I place the increment counter at the right location ?

1 个答案:

答案 0 :(得分:3)

不建议直接翻译,因为你放弃了许多高效的python编码功能。

要在python中正确地执行此操作,您应该1)识别python的0索引约定,并且2)认识到fortran是列主要而python是行主要因此您应该反转所有多维数组的索引顺序

如果你这样做,可以写出循环:

try: 
 r[j,0]=[val for val in u[j] if val > -9999 ][0]
 missing=False
except:
 missing=True

我假设我们实际上并不需要丢失的数值。 如果你需要它,你会有这样的东西:

try: 
 missing,r[j,0]=[(index,val) for (index,val) in enumerate(u[j]) if val > -9999 ][0]
except:
 missing=-1 

您也可以使用速度更快的next,但处理丢失的情况会变得有点棘手。