代码之家  ›  专栏  ›  技术社区  ›  AlexT

如何使用numpy阵列高效地执行多元素交换?

  •  0
  • AlexT  · 技术社区  · 5 年前

    在48个元素的numpy数组中,我需要进行一系列交换。

    34 -> 21 -> 42 -> 26 -> 34
    36 -> 19 -> 44 -> 28 -> 36
    39 -> 16 -> 47 -> 31 -> 39
    

    哪里 x -> y 表示索引x处的元素必须转到yth索引。我正试图想出一个有效的方法来实现这一点,因为这些数字是随机的,这只是我需要进行的一系列交换中的一个。

    例如: 给定以下数组

    original = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
    

    我想进行以下交换

    1 -> 4 -> 6 -> 1
    

    所以我最终得到了

    swapped = ['a', 'g', 'c', 'd', 'b', 'f', 'e', 'h']
    

    所以第一个索引元素变成了第四个索引,第四个索引变成了第六个索引,第六个索引变成了第一个索引。

    2 回复  |  直到 5 年前
        1
  •  2
  •   Homan    5 年前

    这可能是执行其中一个序列最有效的方法:

    swaps = [34, 21, 42, 26, 34]
    arr = np.arange(48)
    
    from_idx = lst[:-1]
    to_idx = lst[1:]
    arr[to_idx] = arr[from_idx]
    
        2
  •  0
  •   Al W    5 年前

    也许是这样的。

    def swap(input, index):
        start_index = index[0]
        for next_index in range(1, len(index)):
           input[start_index], input[next_index] = input[next_index] , input[start_index]
        
        return(input)
    
    if __name__ == '__main__':
        input = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
        index = [2,3,6,2]
    
        output = swap(input, index)
        print(output)