"""演示 numpy 切片是视图、copy() 才是独立副本。""" from __future__ import annotations import numpy as np def main() -> None: arr = np.arange(10) view = arr[2:6] view[0] = 99 print(f"view shares: {np.shares_memory(view, arr)}") print(f"after view: {arr.tolist()}") arr = np.arange(10) copied = arr[2:6].copy() copied[0] = -1 print(f"copy shares: {np.shares_memory(copied, arr)}") print(f"after copy: {arr.tolist()}") arr = np.arange(10) reshaped = arr.reshape(2, 5) reshaped[0, 0] = 77 print(f"reshape shares: {np.shares_memory(reshaped, arr)}") print(f"after reshape: {arr[0]}") if __name__ == "__main__": main()