You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改numpy数组order参数(C行主序转Fortran列主序)为何无效果?

为什么修改numpy数组的order参数后输出完全相同?

我尝试通过修改以下测试脚本中的order参数来验证numpy数组的存储顺序,但无论设置为'C'还是'F',输出结果完全一致,这是为什么?

测试脚本

import numpy as np

# Standard array
arr = [[1, 2, 3], [-7, -8, -9], ['A', 'B', 'C']]
print(arr, '\n')

for row_index, row_entries in enumerate(arr):
    print('Row ' + str(row_index+1))
    for column_index, column_entries in enumerate(row_entries):
        print(' Column ' + str(column_index+1) + '\n', '\t [' + str(column_entries) + ']')

# NumPy array
arr = np.asarray([[1, 2, 3], [-7, -8, -9], ['A', 'B', 'C']], order='F')    # Try 'C' vs. 'F'!!
print('\n\n', arr, '\n')

for row_index, row_entries in enumerate(arr):
    print('Row ' + str(row_index+1))
    for column_index, column_entries in enumerate(row_entries):
        print(' Column ' + str(column_index+1) + '\n', '\t [' + str(column_entries) + ']')

输出结果

[[1, 2, 3], [-7, -8, -9], ['A', 'B', 'C']] 

Row 1
 Column 1
         [1]
 Column 2
         [2]
 Column 3
         [3]
Row 2
 Column 1
         [-7]
 Column 2
         [-8]
 Column 3
         [-9]
Row 3
 Column 1
         [A]
 Column 2
         [B]
 Column 3
         [C]


 [['1' '2' '3']
 ['-7' '-8' '-9']
 ['A' 'B' 'C']] 

Row 1
 Column 1
         [1]
 Column 2
         [2]
 Column 3
         [3]
Row 2
 Column 1
         [-7]
 Column 2
         [-8]
 Column 3
         [-9]
Row 3
 Column 1
         [A]
 Column 2
         [B]
 Column 3
         [C]

原因分析

你看到的输出是数组的逻辑结构,而order参数控制的是数组在内存中的物理存储顺序,两者没有直接关联:

  • 遍历数组(比如enumerate)和打印数组都是按照数组的逻辑结构来访问元素的,不管内存里怎么存储,逻辑上都会以行优先的方式展示。
  • order='C'表示行优先存储(C语言风格),内存中先存完第一行再存第二行;order='F'表示列优先存储(Fortran语言风格),内存中先存完第一列再存第二列,但这些差异不会体现在逻辑遍历和打印上。

验证存储顺序的正确方法

要验证数组的存储顺序,需要查看内存布局相关的属性或方法:

  1. 查看数组的flags属性:通过arr.flags可以看到C_CONTIGUOUS和F_CONTIGUOUS标记,分别对应行优先和列优先存储。
  2. 按不同顺序展平数组:用arr.flatten('C')和arr.flatten('F')分别按行优先、列优先展开数组,对比结果就能看到存储顺序的差异。
  3. 查看内存字节布局:用arr.view(np.uint8)查看数组在内存中的字节排列(适合了解内存结构的用户)。

示例代码

import numpy as np

# 创建不同存储顺序的数组
arr_c = np.asarray([[1, 2, 3], [4, 5, 6]], order='C')
arr_f = np.asarray([[1, 2, 3], [4, 5, 6]], order='F')

# 查看flags标记
print("行优先数组的flags:\n", arr_c.flags)
print("\n列优先数组的flags:\n", arr_f.flags)

# 按不同顺序展平
print("\n按行优先展平(C顺序):", arr_c.flatten('C'))
print("按列优先展平(F顺序):", arr_f.flatten('F'))

示例输出

行优先数组的flags:
   C_CONTIGUOUS : True
   F_CONTIGUOUS : False
   OWNDATA : False
   WRITEABLE : True
   ALIGNED : True
   WRITEBACKIFCOPY : False
   UPDATEIFCOPY : False

列优先数组的flags:
   C_CONTIGUOUS : False
   F_CONTIGUOUS : True
   OWNDATA : False
   WRITEABLE : True
   ALIGNED : True
   WRITEBACKIFCOPY : False
   UPDATEIFCOPY : False

按行优先展平(C顺序): [1 2 3 4 5 6]
按列优先展平(F顺序): [1 4 2 5 3 6]

内容的提问来源于stack exchange,提问作者mattze_frisch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 14:33:23