共計 504 個字符,預計需要花費 2 分鐘才能閱讀完成。
Python 中可以使用多種方法來交換列表中的元素位置,下面列舉了其中幾種常見的方法:
- 使用臨時變量:
def swap_positions(lst, pos1, pos2):
lst[pos1], lst[pos2] = lst[pos2], lst[pos1]
使用臨時變量來交換兩個位置的元素值,通過將 pos1 位置的元素賦給 pos2 位置,將 pos2 位置的元素賦給 pos1 位置來實現交換。
- 使用 pop 和 insert 方法:
def swap_positions(lst, pos1, pos2):
lst.insert(pos1, lst.pop(pos2))
lst.insert(pos2, lst.pop(pos1))
通過先將 pos2 位置的元素彈出并插入到 pos1 位置,再將 pos1 位置的元素彈出并插入到 pos2 位置來實現交換。
- 使用切片:
def swap_positions(lst, pos1, pos2):
lst[pos1], lst[pos2] = lst[pos2], lst[pos1]
通過將 pos1 位置和 pos2 位置的元素切片賦給對方來實現交換。
以上都是常見的方法,具體使用哪種方法取決于個人的喜好和實際情況。
丸趣 TV 網 – 提供最優質的資源集合!
正文完