本篇代码在Julia1.0.2中测试通过
For循环的使用方法
for i in 1:5
print(i, ", ")
end
println()
# 程序输出: 1, 2, 3, 4, 5,
# 循环的定义中,in和等号=是等价的(所以这里两种用法换来换去)
for i = 1:5
print(i, ", ")
end
println()
# 程序输出: 1, 2, 3, 4, 5,
# 数组可以直接循环遍历
a1 = [1,2,3,4]
for i in a1
print(i, ", ")
end
println()
# 程序输出: 1, 2, 3, 4,
# continue和break方法和在Python中的用法一致
a2 = collect(1:20)
for i in a2
if i % 2 != 0
continue
end
print(i, ", ")
if i >= 8
break
end
end
println()
# 程序输出: 2, 4, 6, 8,
循环的特殊使用方法
a1 = [1,2,3,4]
# 如果数组在循环体中有操作的话则只能使用while循环
# pop方法可以用来除去数组的最后一个元素
while !isempty(a1)
print(pop!(a1), ", ")
end
println()
# 程序输出: 4, 3, 2, 1,
d1 = Dict(1=>"one", 2=>"two", 3=>"three")
# 字典可以通过keys函数来参与循环
for k in sort(collect(keys(d1)))
print(k, ": ", d1[k], ", ")
end
println()
# 程序输出: 1: one, 2: two, 3: three,
# 和Python中一样,enumerate(枚举)可以允许在循环中同时获得数组元素的位置和值
a3 = ["one", "two", "three"]
for (i, v) in enumerate(a3)
print(i, ": ", v, ", ")
end
println()
# 程序输出: 1: one, 2: two, 3: three,
# (注意,和Python不一样的是,枚举方法的指针是从1开始的)
Map函数
# map函数和大家所了解的一致,它会应用于数组或是迭代器得到的每一个元素
a4 = map((x) -> x^2, [1, 2, 3, 7])
print(a4)
# 程序输出: 4-element Array{Int64,1}: [1,4,9,49]

点击阅读原文可查看历史文章
网友评论