【发布时间】:2017-04-15 15:28:26
【问题描述】:
是否有与 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 与 NumPy 和 Fortran 在表现力和功能方面非常相似。这颗罗塞塔石碑展示了如何同时在两种语言中实现许多常见的习语。 fortran90.org/src/rosetta.html
-
这个问题应该和equivalent question for C++联系起来,特别是因为Fortran和C++都是编译的,OO语言,所以建议的解决方案是相似的。