Bắt đầu ngayBắt đầu miễn phí

Looping over nested structures

You've seen how you can loop over a vector to return the values within that vector. One step further than this is to loop over a vector of vectors, returning the corresponding values in order. This can be referred to as a 'nested' structure, where one vector is inside another vector. You'll often find nested structures in practice, so understanding how to iterate over these structures and extract data from them is an important skill to have.

In this example, we have changed our previous stock_tickers vector to include the current stock price of each ticker, and we have renamed the vector to stocks. Note the structure of the nested vector below.

4-element Vector{Vector{Any}}:
 ["AAPL", 151]
 ["AMZN", 94]
 ["GOOG", 97]
 ["MSFT", 241]

Bài tập này là một phần của khóa học

Intermediate Julia

Xem khóa học

Hướng dẫn bài tập

  • Loop over the nested vector stocks to return the stock ticker and price for each ticker in the vector.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

# Loop over stocks, printing the ticker and the price
for (ticker, price) in ____
    println("The price of 1 ____ share is ____.")
end
Chỉnh sửa và Chạy Mã