官术网_书友最值得收藏!

for loops

We already encountered the for loop when iterating over the element e of a collection coll (refer to the StringsRanges and Arrays sections in Chapter 2, Variables, Types, and Operations). This takes the following general form:

# code in Chapter 4\repetitions.jl 
for e in coll 
   # body: process(e) executed for every element e in coll 
end

Here, coll can be a range, a string, an array, or any other iterable collection (for other uses, also refer to Chapter 5, Collection Types). The variable e is not known outside the for loop. When iterating over a numeric range, often = (equal to) is used instead of in:

    for n = 1:10   
       print(n^3)   
    end 

(This code can be a one-liner, but is spread over three lines for clarity.) The for loop is generally used when the number of repetitions is known.

Use for i in 1:n rather than for i in [1:n] since the latter allocates an array while the former uses a simpler range object.

You can also use ? instead of in or =.

If you need to know the index when iterating over the elements of an array, run the following code:

arr = [x^2 for x in 1:10] 
for i = 1:length(arr)
println("the $i-th element is $(arr[i])") end

A more elegant way to accomplish this uses the enumerate function, as follows:

for (ix, val) in enumerate(arr)
println("the $ix-th element is $val") end

Nested for loops are possible, as in this code snippet, for a multiplication table:

for n = 1:5 
    for m = 1:5 
        println("$n * $m = $(n * m)") 
    end 
end 

However, nested for loops can often be combined into a single outer loop, as follows:

for n = 1:5, m = 1:5 
    println("$n * $m = $(n * m)") 
end

主站蜘蛛池模板: 延津县| 靖远县| 大宁县| 衡山县| 万宁市| 永善县| 安庆市| 汪清县| 徐水县| 高要市| 东乌珠穆沁旗| 江永县| 静乐县| 青河县| 大埔县| 乐安县| 永宁县| 安庆市| 儋州市| 米脂县| 博野县| 高平市| 灵璧县| 慈利县| 伊宁市| 锦州市| 宝丰县| 太原市| 昔阳县| 庆安县| 额济纳旗| 明水县| 克拉玛依市| 确山县| 建阳市| 曲周县| 宕昌县| 新密市| 萍乡市| 天柱县| 德昌县|