有没有一个Fortran等价于Python的forelse语句?

2024-09-30 16:26:08 发布

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

有没有一个Fortran等效的Python for else语句?在

例如,下面将数字列表按不同的范围排序。在Python中,它是:

absth = [1, 2, 3, 4, 5]
vals = [.1, .2, .5, 1.2, 3.5, 3.7, 16.8, 19.8, 135.60]


counts = [0] * len(absth)
for v in vals:
    for i, a in enumerate(absth):
        if v < a:
            counts[i] += 1
            break
    else:
        counts[-1] += 1

在Fortran中,这是相同的:

^{pr2}$

但是有没有一种方法可以不必使用is_in_last_absth并用类似Python中的else来替换它?在


Tags: in列表forlenif排序数字语句
3条回答

如果这个问题是关于二进制一系列数字的具体问题,其中absth是每个bin的上限(bar最后一个没有上限),那么我可能会这样写:

PROGRAM test

  IMPLICIT NONE

  INTEGER :: ix   
  INTEGER, DIMENSION(5) :: absth = [1, 2, 3, 4, 5]   
  REAL, DIMENSION(9) :: vals = [.1, .2, .5, 1.2, 3.5, 3.7, 16.8, 19.8, 135.60]   
  INTEGER, DIMENSION(SIZE(absth)+1) :: bins

  bins = 0

  DO ix = 1, SIZE(bins)-1
     bins(ix) = COUNT(vals<absth(ix))   
  END DO   
  bins(ix) = COUNT(vals)

  bins = bins-EOSHIFT(bins,-1)
  WRITE(*,*) 'bins = ', bins
  ! which writes  3  1  0  2  0  3

END PROGRAM test

然后,当我对逻辑是正确的感到高兴时,我会把它转换成一个函数,并添加一些错误检查。在

如果问题更一般,并且问到什么是Fortran(90后)惯用的方法来重现Python的for-else结构,这里也有答案。在

没有直接等价于python构造的。在

但是请注意,使用计数循环控制的do循环的提前终止可以通过检查循环后do变量的值来检测。在

do iv = 1, nvals
  do ia = 1, nabsth - 1
    if (vals(iv) < absth(ia)) then
      counts(ia) = counts(ia) + 1
      exit
    end if
  end do

  ! If the loop terminates because it completes the iteration 
  ! count (and not because the exit statement is executed) then 
  ! the do variable is one step beyond the value it had 
  ! during the last iteration.
  if (ia == nabsth) then
    counts(nabsth) = counts(nabsth) + 1
  end if
end do

exit语句还可以跳出不仅仅是do循环:

^{pr2}$

循环语句可以循环该语句嵌套的任何do构造:

outer_loop: do iv = 1, nvals
  do ia = 1, nabsth - 1
    if (vals(iv) < absth(ia)) then
      counts(ia) = counts(ia) + 1
      cycle outer_loop
    end if
  end do

  counts(nabsth) = counts(nabsth) + 1
end do outer_loop

GO TO语句允许任意跳转。特别是,编写for循环后接else块,然后是标记为continue的。在循环中,如果条件为真,则跳转到标记为continue的。否则for循环将正常终止,else块将被执行,然后继续,这与python for…else构造的语义完全匹配。在

例如:

        INTEGER nabsth, nvals
        PARAMETER (nabsth=5, nvals=9)
        INTEGER absth(nabsth), counts(nabsth)
        REAL vals(nvals)
        DATA absth/1, 2, 3, 4, 5/
        DATA counts/0, 0, 0, 0, 0/
        DATA vals/.1, .2, .5, 1.2, 3.5, 3.7, 16.8, 19.8, 135.60/

        do iv = 1, nvals

          do ia = 1, nabsth - 1
            if (vals(iv) < absth(ia)) then
              counts(ia) = counts(ia) + 1
              goto 10
            end if
          end do
          counts(nabsth) = counts(nabsth) + 1
10        continue
        end do
        WRITE (*,*), counts
        end

生产

^{pr2}$

相关问题 更多 >