Skip to main content
 首页 » 编程设计

python之是否有与 Python 的 for-else 语句等效的 Fortran 语句

2025年05月04日10jillzhang

是否有与 Python 的 for-else 语句等效的 Fortran 语句?

例如,以下将数字列表排序为不同的范围。在 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 中,这也是一样的:

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

但有没有办法不必使用 is_in_last_absth 并将其替换为类似 Python 中的 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 循环:

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

循环语句可以循环语句嵌套在其中的任何 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