リスト要素を回転させる

PythonPythonBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

このチャレンジでは、指定された要素数だけリストを回転させる関数を作成することが求められます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") subgraph Lab Skills python/comments -.-> lab-13711{{"リスト要素を回転させる"}} python/lists -.-> lab-13711{{"リスト要素を回転させる"}} python/tuples -.-> lab-13711{{"リスト要素を回転させる"}} python/function_definition -.-> lab-13711{{"リスト要素を回転させる"}} end

リスト要素を回転させる

roll(lst, offset) という関数を書きなさい。この関数は、リスト lst と整数 offset を引数に取ります。この関数は、指定された要素数をリストの先頭に移動させる必要があります。offset が正の場合、要素はリストの末尾から先頭に移動される必要があります。offset が負の場合、要素はリストの先頭から末尾に移動される必要があります。

修正されたリストを返します。

def roll(lst, offset):
  return lst[-offset:] + lst[:-offset]
roll([1, 2, 3, 4, 5], 2) ## [4, 5, 1, 2, 3]
roll([1, 2, 3, 4, 5], -2) ## [3, 4, 5, 1, 2]

まとめ

このチャレンジでは、指定された要素数だけリストを回転させる方法を学びました。リストの 2 つのスライスを取得し、返す前にそれらを結合するためにスライス表記を使用しました。