最小要素のインデックス

PythonPythonBeginner
今すぐ練習

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

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

はじめに

Python では、min() 関数を使ってリストの最小値を簡単に見つけることができます。ただし、その最小値のインデックスも知りたい場合はどうでしょうか。このチャレンジでは、リストの中で最小値を持つ要素のインデックスを返す関数を作成します。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/comments -.-> lab-13694{{"最小要素のインデックス"}} python/lists -.-> lab-13694{{"最小要素のインデックス"}} python/tuples -.-> lab-13694{{"最小要素のインデックス"}} python/function_definition -.-> lab-13694{{"最小要素のインデックス"}} python/build_in_functions -.-> lab-13694{{"最小要素のインデックス"}} end

最小要素のインデックス

整数のリスト arr を引数として受け取り、リスト内の最小値を持つ要素のインデックスを返す関数 min_element_index(arr) を作成します。

この問題を解くには、min() 関数を使ってリスト内の最小値を取得し、その後 list.index() メソッドを使ってそのインデックスを返します。

def min_element_index(arr):
  return arr.index(min(arr))
min_element_index([3, 5, 2, 6, 10, 7, 9]) ## 2

まとめ

このチャレンジでは、Python を使ってリスト内の最小値を持つ要素のインデックスを見つける方法を学びました。min() 関数と list.index() メソッドを使うことで、リスト内の最小値のインデックスを簡単に取得できます。