- Julia 1.0 Programming Complete Reference Guide
- Ivo Balbaert Adrian Salceanu
- 300字
- 2021-06-24 14:21:46
for loops
We already encountered the for loop when iterating over the element e of a collection coll (refer to the Strings, Ranges 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.
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
- 基于粒計算模型的圖像處理
- INSTANT OpenCV Starter
- Building a Game with Unity and Blender
- 編寫整潔的Python代碼(第2版)
- VMware vSphere 6.7虛擬化架構實戰指南
- Julia機器學習核心編程:人人可用的高性能科學計算
- iOS應用逆向工程(第2版)
- Symfony2 Essentials
- 編程改變生活:用Python提升你的能力(進階篇·微課視頻版)
- Learning Splunk Web Framework
- Python預測分析與機器學習
- 深入大型數據集:并行與分布化Python代碼
- Zend Framework 2 Cookbook
- 可視化H5頁面設計與制作:Mugeda標準教程
- C#程序開發參考手冊