リスト内のランダムな要素

PythonPythonBeginner
今すぐ練習

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

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

はじめに

Python では、random モジュールを使って、リストからランダムな要素を簡単に取得できます。このモジュールには、指定されたリストからランダムな要素を返す choice() という関数があります。このチャレンジでは、引数としてリストを受け取り、そのリストからランダムな要素を返す関数を書くように求められます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/PythonStandardLibraryGroup -.-> python/math_random("Math and Random") subgraph Lab Skills python/comments -.-> lab-13712{{"リスト内のランダムな要素"}} python/lists -.-> lab-13712{{"リスト内のランダムな要素"}} python/tuples -.-> lab-13712{{"リスト内のランダムな要素"}} python/function_definition -.-> lab-13712{{"リスト内のランダムな要素"}} python/importing_modules -.-> lab-13712{{"リスト内のランダムな要素"}} python/using_packages -.-> lab-13712{{"リスト内のランダムな要素"}} python/standard_libraries -.-> lab-13712{{"リスト内のランダムな要素"}} python/math_random -.-> lab-13712{{"リスト内のランダムな要素"}} end

リスト内のランダムな要素

引数としてリストを受け取り、そのリストからランダムな要素を返す random_element(lst) 関数を書きなさい。

  • random.choice() を使って、lst からランダムな要素を取得します。
from random import choice

def sample(lst):
  return choice(lst)
sample([3, 7, 9, 11]) ## 9

まとめ

このチャレンジでは、Python の random モジュールを使ってリストからランダムな要素を取得する方法を学びました。また、引数としてリストを受け取り、そのリストからランダムな要素を返す関数を書きました。Python でリストを扱う際に役立つスキルです。