我正在研究旋轉串列,并制作了一個左右旋轉串列的功能,但是如何撰寫旋轉多少次的代碼?如果這是有道理的。我想將它作為引數傳遞給函式。
table = [1, 10 ,20, 0, 59, 86, 32, 11, 9, 40]
def rotate_left():
(table.append(table.pop(0)))
return table
print(rotate_left())
def rotate_right():
(table.insert(0,table.pop()))
return table
print(rotate_right())
uj5u.com熱心網友回復:
您可以for loop在函式內部使用并傳遞要旋轉的次數作為引數。
table = [1, 10 ,20, 0, 59, 86, 32, 11, 9, 40]
def rotate_left(rotate_times):
for _ in range(rotate_times):
table.append(table.pop(0))
return table
>>> print(rotate_left(2))
>>> [20, 0, 59, 86, 32, 11, 9, 40, 1, 10]
def rotate_right(rotate_times):
for _ in range(rotate_times):
table.insert(0,table.pop())
return table
>>> print(rotate_right(2))
>>> [1, 10, 20, 0, 59, 86, 32, 11, 9, 40]
筆記
在上面的場景中,請注意這樣一個事實,當您將 a 傳遞list給一個方法并在該方法內對其進行修改時,original list除非您制作 a ,否則會進行更改deep copy,因為list它是一種mutable型別。
因此,當您呼叫 時rotate_left(2),它會向左旋轉original list兩次。然后,當您呼叫 時rotate_right(2),它會旋轉original list已旋轉 的rotate_left(2),因此我們按初始順序獲得串列。
由于函式已經在修改original list,您可以return table從函式中洗掉(除非您想要新的串列深層副本)。然后簡單地列印串列,如:
def rotate_left(rotate_times):
for _ in range(rotate_times):
table.append(table.pop(0))
>>> rotate_left(2)
>>> print(table)
>>> [20, 0, 59, 86, 32, 11, 9, 40, 1, 10]
uj5u.com熱心網友回復:
您可以撰寫一個“for 回圈”并使用“范圍”來決定要旋轉多少次。在此示例中,“rotate_left()”被呼叫了 3 次:
table = [1, 10 ,20, 0, 59, 86, 32, 11, 9, 40]
def rotate_left():
(table.append(table.pop(0)))
return table
def rotate_right():
(table.insert(0,table.pop()))
return table
for i in range(3):
print(rotate_left())
uj5u.com熱心網友回復:
您可以撰寫一個“回圈”并使用“范圍”來決定要回圈多少次。在這個例子中,有一個程式詢問用戶在哪個方向和多少次轉動和計算。
def rotate_left(count,table):
for i in range (count):
(table.append(table.pop(0)))
return table
def rotate_right(count,table):
for i in range (count):
(table.insert(0,table.pop()))
return table
def main():
table = [1, 10 ,20, 0, 59, 86, 32, 11, 9, 40]
isSelect = True
while(isSelect):
rotate = int(input("1- Rotate Left\n2- Rotate Right\n: "))
count = int(input("\nHow many times to rotate ?\n: "))
if((rotate == 1 or rotate == 2) and count > 0):
isSelect = False
if (rotate == 1):
print(rotate_left(count,table))
elif (rotate == 2):
print(rotate_right(count,table))
else:
print("\nInvalid Parameter. Please choose again.\n")
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492952.html
標籤:Python
下一篇:回圈中重復相同的輸出
