Python中数组矩阵的翻转(翻转180度,向左翻转90度,向右翻转90度)

Python中数组矩阵的翻转(翻转180度,向左翻转90度,向右翻转90度)

转载请表明原处:https://blog.csdn.net/kane7csdn/article/details/83928848


先定义数组:

a = np.array(([1, 2, 3], [4, 5, 6], [7, 8, 9]))
a4d = np.array(([1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]))
b = np.array(([1, 2, 3], [4, 5, 6]))
# [[1 2 3]
#  [4 5 6]
#  [7 8 9]]

# [[1 2 3 4]
#  [2 3 4 5]
#  [3 4 5 6]
#  [4 5 6 7]]

# [[1 2 3]
#  [4 5 6]]

翻转180度:

def flip180(arr):
    new_arr = arr.reshape(arr.size)
    new_arr = new_arr[::-1]
    new_arr = new_arr.reshape(arr.shape)
    return new_arr
print(flip180(a))
# [[9 8 7]
#  [6 5 4]
#  [3 2 1]]
print(flip180(a4d))
# [[7 6 5 4]
#  [6 5 4 3]
#  [5 4 3 2]
#  [4 3 2 1]]
print(flip180(b))
# [[6 5 4]
#  [3 2 1]]

向左翻转90度:

def flip90_left(arr):
    new_arr = np.transpose(arr)
    new_arr = new_arr[::-1]
    return new_arr
print(flip90_left(a))
# [[3 6 9]
#  [2 5 8]
#  [1 4 7]]
print(flip90_left(a4d))
# [[4 5 6 7]
#  [3 4 5 6]
#  [2 3 4 5]
#  [1 2 3 4]]
print(flip90_left(b))
# [[3 6]
#  [2 5]
#  [1 4]]

向右翻转90度:

def flip90_right(arr):
    new_arr = arr.reshape(arr.size)
    new_arr = new_arr[::-1]
    new_arr = new_arr.reshape(arr.shape)
    new_arr = np.transpose(new_arr)[::-1]
    return new_arr
print(flip90_right(a))
# [[7 4 1]
#  [8 5 2]
#  [9 6 3]]
print(flip90_right(a4d))
# [[4 3 2 1]
#  [5 4 3 2]
#  [6 5 4 3]
#  [7 6 5 4]]
print(flip90_right(b))
# [[4 1]
#  [5 2]
#  [6 3]]

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值