在閱讀NumPy User Guide中3.11節(jié)Can you reshape an array?時(shí)蕉汪,看到函數(shù)reshape()涉及到一個(gè)參數(shù)“order”。可選項(xiàng)有C\F\A三項(xiàng)严肪,很疑惑這個(gè)參數(shù)有什么含義,查閱了相關(guān)資料隅津,把收獲放在下面吧诬垂。
首先看文檔中對(duì)這個(gè)參數(shù)的解釋:
order: C means to read/write the elements using C-like index order,F means to read/write the elements using Fortran-like index order,A means to read/write the elements in Fortran-like index order if a is Fortran contiguous in memory,C-like order otherwise. (This is an optional parameter and doesn’t need to be specified.)Essentially, C and Fortran orders have to do with how indices correspond to the order the array is stored in memory.In Fortran, when moving through the elements of a two-dimensional array as it is stored in memory, the first index is the most rapidly varying index. As the first index moves to the next row as it changes, the matrix is stored one column at a time. This is why Fortran is thought of as a Column-major language. In C on the other hand, the last index changes the most rapidly. The matrix is stored by rows, making it a Row-major language. What you do for C or Fortran depends on whether it’s more important to preserve the indexing convention or not reorder the data.
order:C表示使用類似C的索引順序讀取/寫入元素劲室,F(xiàn)表示使用類似Fortran的索引順序讀取/寫入元素伦仍,A表示如果數(shù)組a在內(nèi)存中以Fortran形式連續(xù),則以類似Fortran的索引順序讀取/寫入元素很洋,否則為C類順序充蓝。 (這是一個(gè)可選參數(shù),不需要指定喉磁。)本質(zhì)上谓苟,C和Fortran順序與索引如何與數(shù)組在內(nèi)存中存儲(chǔ)的順序相對(duì)應(yīng)有關(guān)。在Fortran中协怒,當(dāng)移動(dòng)兩個(gè)元素時(shí) 三維數(shù)組存儲(chǔ)在內(nèi)存中時(shí)涝焙,第一個(gè)索引是變化最快的索引。 當(dāng)?shù)谝粋€(gè)索引更改時(shí)移動(dòng)到下一行時(shí)孕暇,矩陣一次存儲(chǔ)一列仑撞。 這就是為什么將Fortran視為Column-major language的原因。 另一方面妖滔,在C中隧哮,最后一個(gè)索引變化最快。 矩陣按行存儲(chǔ)座舍,使其成為Row-major language沮翔。 對(duì)C或Fortran的處理方式取決于保留索引約定還是不對(duì)數(shù)據(jù)重新排序更為重要。
大致明白了曲秉,order是指定索引與數(shù)組元素對(duì)應(yīng)方式的一個(gè)參數(shù)采蚀,也就是決定了數(shù)組元素在內(nèi)存中的存儲(chǔ)方式。一共有兩種存儲(chǔ)方式:Column-major和Row-major承二。Fortran語(yǔ)言是前者的代表(也就是說(shuō)Fortran語(yǔ)言是用Column-major方式在內(nèi)存中存儲(chǔ)數(shù)據(jù)的)榆鼠,C語(yǔ)言是后者的代表。NumPy中設(shè)置這個(gè)參數(shù)矢洲,目的是避免不同數(shù)據(jù)源(尤其是存儲(chǔ)方式不同的)數(shù)據(jù)傳遞的時(shí)候出現(xiàn)存儲(chǔ)錯(cuò)誤璧眠。
下面再看看Column-major和Row-major:
參考資料:
https://blog.csdn.net/lanchunhui/article/details/55656288