首頁  >  文章  >  後端開發  >  如何向左或向右旋轉 Python 清單?

如何向左或向右旋轉 Python 清單?

Susan Sarandon
Susan Sarandon原創
2024-10-19 17:39:02842瀏覽

How to Rotate a Python List Left or Right?

Python 清單旋轉

簡介:
旋轉Python 清單涉及將其元素向左或向右移動指定數量的位置.

方法一:
問題:如何將清單向左旋轉?
答案:

<code class="python">def rotate_left(l, n):
    return l[n:] + l[:n]</code>

示例:

<code class="python">example_list = [1, 2, 3, 4, 5]
result = rotate_left(example_list, 2)
print(result)  # Output: [3, 4, 5, 1, 2]</code>

方法2:
問題:如何將清單旋轉到對嗎?
答案:

<code class="python">def rotate_right(l, n):
    return l[-n:] + l[:-n]</code>

示例:

<code class="python">example_list = [1, 2, 3, 4, 5]
result = rotate_right(example_list, 2)
print(result)  # Output: [4, 5, 1, 2, 3]</code>

解釋:
兩種方法都使用切片來建立新清單:

  • 左旋轉: l[n:] 切片包含從第n 個位置到末尾的元素,而l[:n]包含從開始到第n 個位置的元素。
  • 右旋轉: l[-n:] 切片包含列表最後n 個位置的元素,而l[:-n ] 包括從開始到倒數第二個第n 個位置的元素。

然後透過連接這些切片形成結果移位清單。

以上是如何向左或向右旋轉 Python 清單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn