imm*_*ied 3 python fortran for-else
是否有 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
Run Code Online (Sandbox Code Playgroud)
在 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
Run Code Online (Sandbox Code Playgroud)
但是有没有办法不用is_in_last_absth像elsePython 中的那样使用和替换它?
没有直接等价于那个 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
Run Code Online (Sandbox Code Playgroud)
退出语句还可以跳出不仅仅是 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
Run Code Online (Sandbox Code Playgroud)
并且循环语句可以循环该语句嵌套在其中的任何 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
Run Code Online (Sandbox Code Playgroud)