通过同时分配交换numpy 2d-array的元素会覆盖元素

时间:2018-01-03 04:25:13

标签: python arrays python-3.x numpy swap

我通常使用Python作为我的主要编程语言之一。

我观察到通过同时分配交换numpy 2d-array的行会覆盖元素。我觉得奇怪的是这种覆盖只发生在:

  • 2d-array

并且,没有发生:

  • list_of_list
  • list_of_array
  • array_1d
  • list_of_numbers

(请参阅以下“案例1”结果。)

我想知道这种行为的机制。这是我的测试代码:

import numpy as np
def swap(seq):
    '''swaps first two elemnts'''
    print('Before swapping\n', seq)
    seq[0], seq[1] = seq[1], seq[0]
    print('After swapping\n', seq)
    print('')

print('Case 1: array_2d')
array_2d = np.arange(8).reshape(4, 2)
swap(array_2d)

print('Case 2: list_of_list')
list_of_list = [[0, 1], [2, 3], [4, 5], [6, 7]]
swap(list_of_list)

print('Case 3: list_of_array')
list_of_array = [np.array([0, 1]),
                 np.array([2, 3]),
                 np.array([4, 5]),
                 np.array([6, 7])]
swap(list_of_array)

print('Case 4: array_1d')
array_1d = np.arange(4)
swap(array_1d)

print('Case 5: list_of_numbers')
list_of_numbers = list(range(4))
swap(list_of_numbers)

结果是:

Case 1: array_2d
Before swapping
 [[0 1]
 [2 3]
 [4 5]
 [6 7]]
After swapping
 [[2 3]  # <- failed to swap
 [2 3]   # <- failed to swap
 [4 5]
 [6 7]]

Case 2: list_of_list
Before swapping
 [[0, 1], [2, 3], [4, 5], [6, 7]]
After swapping
 [[2, 3], [0, 1], [4, 5], [6, 7]]

Case 3: list_of_array
Before swapping
 [array([0, 1]), array([2, 3]), array([4, 5]), array([6, 7])]
After swapping
 [array([2, 3]), array([0, 1]), array([4, 5]), array([6, 7])]

Case 4: array_1d
Before swapping
 [0 1 2 3]
After swapping
 [1 0 2 3]

Case 5: list_of_numbers
Before swapping
 [0, 1, 2, 3]
After swapping
 [1, 0, 2, 3]

我发现以下帖子涉及同时分配,但仍无法理解上述行为。

使用.copy()方法的解决方案。

同时转让的评估顺序。

我很欣赏任何提示。

感谢。

0 个答案:

没有答案