我想在python中按范圍交換元素串列
我的代碼是
List = [1,2,3,4,5,6]
def swap(list_, a, b):
list_[a], list_[b] = list_[b], list_[a]
swap(List, 0, 5,)
print(List)
我的輸出是
[6, 2, 3, 4, 5, 1]
但我想要的是由串列索引范圍交換
# my expected output
n = 2 (add var by input)
#and it swapped to this
[3, 4, 5, 6, 1, 2]
uj5u.com熱心網友回復:
你可以使用這樣的東西:
def swap(List, n):
return List[n:] List[:n]
List = [1,2,3,4,5,6]
n = input()
print(swap(List, n))
使用 slice (:) 您可以按索引拆分子串列中的串列。然后你可以在 return 陳述句中重新組合它們
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/399270.html
下一篇:用括號括起來的元素分割字串
