編寫一個 Python 程序,將 Numpy 數組向左旋轉 n 次或N
個位置。為了向左旋轉數組,我們根據位置對數組進行了切片,並將其與 Python 示例中的 numpy concatenate 函數相結合。
import numpy as np
ltArray = np.array([4, 7, 9, 11, 22, 55, 99, 125, 78, 345])
ltRotate = int(input("Enter Position to Left Rotate Array Elements = "))
print('Original Array Elements Before Left Rotating')
print(ltArray)
arr = np.concatenate((ltArray[ltRotate:], ltArray[:ltRotate]), axis = 0)
print('\nFinal Array Elements After Left Rotating')
print(arr)
這個 Python 程序使用 for 循環根據用戶給定的位置向左旋轉 Numpy 數組項。
import numpy as np
ltArray = np.array([19, 25, 32, 77, 28, 99, 44, 88])
ltRotate = int(input("Enter Position to Left Rotate Array Elements = "))
print('Original Array Elements Before Left Rotating')
print(ltArray)
for i in range(ltRotate):
firstValue = ltArray[0]
for j in range(len(ltArray) - 1):
ltArray[j] = ltArray[j + 1]
ltArray[len(ltArray) - 1] = firstValue
print('\nFinal Array Elements After Left Rotating')
print(ltArray)
Enter Position to Left Rotate Array Elements = 5
Original Array Elements Before Left Rotating
[19 25 32 77 28 99 44 88]
Final Array Elements After Left Rotating
[99 44 88 19 25 32 77 28]
在這個 Python 例子中,leftRotateArray 函數將把任意數組項旋轉到左手邊,printArrayItems 列印數組項。
import numpy as np
def printArrayItems(ltArray):
for i in ltArray:
print(i, end = ' ')
def leftRotateArray(ltArray, ltRotate):
for i in range(ltRotate):
firstValue = ltArray[0]
for j in range(len(ltArray) - 1):
ltArray[j] = ltArray[j + 1]
ltArray[len(ltArray) - 1] = firstValue
ltArray = np.random.randint(11, 110, size = 10)
ltRotate = int(input("\nEnter Position to Left Rotate Array Elements = "))
print('Original Array Elements Before Left Rotating')
printArrayItems(ltArray)
leftRotateArray(ltArray, ltRotate)
print('\nFinal Array Elements After Left Rotating')
printArrayItems(ltArray)
Enter Position to Left Rotate Array Elements = 7
Original Array Elements Before Left Rotating
73 45 65 97 84 99 40 18 77 105
Final Array Elements After Left Rotating
18 77 105 73 45 65 97 84 99 40
Python 程序使用 while 循環向左旋轉 Numpy 數組 n。
import numpy as np
def printArrayItems(ltArray):
i = 0
while i < len(ltArray):
print(ltArray[i], end = ' ')
i = i + 1
def leftRotateArray(ltArray, ltRotate):
i = 0
while(i < ltRotate):
firstValue = ltArray[0]
j = 0
while(j < len(ltArray) - 1):
ltArray[j] = ltArray[j + 1]
j = j + 1
ltArray[len(ltArray) - 1] = firstValue
i = i + 1
ltArray = np.random.randint(70, 500, size = 15)
ltRotate = int(input("\nEnter Position to Left Rotate Array Elements = "))
print('Original Array Elements Before Left Rotating')
printArrayItems(ltArray)
leftRotateArray(ltArray, ltRotate)
print('\nFinal Array Elements After Left Rotating')
printArrayItems(ltArray)
Enter Position to Left Rotate Array Elements = 6
Original Array Elements Before Left Rotating
204 76 370 211 180 453 407 250 213 332 456 333 292 460 354
Final Array Elements After Left Rotating
407 250 213 332 456 333 292 460 354 204 76 370 211 180 453
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/227491.html