有没有一个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
来替换它?在
如果这个问题是关于二进制一系列数字的具体问题,其中
absth
是每个bin的上限(bar最后一个没有上限),那么我可能会这样写:然后,当我对逻辑是正确的感到高兴时,我会把它转换成一个函数,并添加一些错误检查。在
如果问题更一般,并且问到什么是Fortran(90后)惯用的方法来重现Python的
for-else
结构,这里也有答案。在没有直接等价于python构造的。在
但是请注意,使用计数循环控制的do循环的提前终止可以通过检查循环后do变量的值来检测。在
exit语句还可以跳出不仅仅是do循环:
^{pr2}$循环语句可以循环该语句嵌套的任何do构造:
GO TO语句允许任意跳转。特别是,编写for循环后接else块,然后是标记为continue的。在循环中,如果条件为真,则跳转到标记为continue的。否则for循环将正常终止,else块将被执行,然后继续,这与python for…else构造的语义完全匹配。在
例如:
生产
^{pr2}$相关问题 更多 >
编程相关推荐