【Python入門】複数の要素番号を用いてリスト(配列)の要素を取得する方法とは?複数の要素番号を用いてリスト(配列)の要素の取得方法を徹底解説

Python

Pythonのリスト(配列)とは、複数の要素を格納できるデータ型の1つで、要素の順序を保持します。リストは角かっこ [] で囲まれ、カンマ , で区切られた複数の要素を含むことができます。リストの要素には、異なるデータ型のオブジェクトを含むことができます。また、リストは可変(mutable)オブジェクトであり、要素を追加、削除、更新することができます。本記事では、Pythonによる複数の要素番号を用いてリスト(配列)の要素を取得する方法を紹介します。

下記の様な内容で悩んでいる/困っている場合に使える方法を参考までにご共有させて頂きます。

・Pythonの場合、どうやって配列の要素を取得するの?
・Pythonのリスト(配列)は、どの様にリスト(配列)の要素を取得するのだろうか?

複数の要素番号を用いてリスト(配列)の要素の取得(自作関数)

関数の定義

def getElementsOfListByID(input_list: list, from_id:int=0, to_id:int=None, step_id:int=1) -> list:
    if (to_id==None) or (to_id > len(input_list)-1): to_id = len(input_list)-1
    if 0 > from_id: from_id=0
    return [input_list[str_id] for str_id in range(from_id, to_id+1, step_id)]

使用例1

SampleList = [0,1,2,3,4,5,6,7,8,9]
ElementsOfListByID = getElementsOfListByID(SampleList)
print(f"Elements Of List By ID:\n{ElementsOfListByID} {type(ElementsOfListByID)}")
Elements Of List By ID:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>

使用例2

SampleList = [0,1,2,3,4,5,6,7,8,9]
ElementsOfListByID = getElementsOfListByID(SampleList, 1, 5)
print(f"Elements Of List By ID:\n{ElementsOfListByID} {type(ElementsOfListByID)}")
Elements Of List By ID:
[1, 2, 3, 4, 5] <class 'list'>

使用例3

SampleList = [0,1,2,3,4,5,6,7,8,9]
ElementsOfListByID = getElementsOfListByID(SampleList, 2, 10, 2)
print(f"Elements Of List By ID:\n{ElementsOfListByID} {type(ElementsOfListByID)}")
Elements Of List By ID:
[2, 4, 6, 8] <class 'list'>

まとめ

Pythonのリスト(配列)はPython標準で使えるデータ型であり、Pythonでプログラムする上でよく使うものとなっております。この記事では、Pythonによる複数の要素番号を用いてリスト(配列)の要素を取得する方法を紹介しました。ぜひ活用してみてください。

関連検索ワード

How to get elements of list by index list?

関連キーワード

python, 入門, 初心者, リスト, 配列, 複数, 要素, 取得, list, multiple, element, get

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny