LoginSignup
0
0

More than 5 years have passed since last update.

Aidemy3回目 メモ 「9/22」

Posted at

Aidemy | 10秒で始めるAIプログラミング学習サービスAidemy[アイデミー」
https://aidemy.net/

本日3回目メモ。

Aidemy3回目メモ

リストのインデックス

自動でインデックス(index) が割り振られる。
インデックスの 先頭は「0」 で、その後1、2、3…と順番に続く。

TestList = [1, 2, 3, 4]
print(TestList [1])  #インデックスが1の「2」が出力される

リストインデックスはマイナス値を指定する事で末尾からいくつめ、という指定もできる。

TestList = [1, 2, 3, 4]
print(TestList [-1])  #インデックスが末尾の「4」が出力される

スライス

リストから一部の要素を切り出す事をスライス、という。

TestList = [1, 2, 3, 4]

スライスの仕方

書き方 説明
TestList[1:3] インデックス1~2の要素
TestList[1:] インデックス1~末尾の要素
TestList[:3] インデックス先頭~2の要素

注意:
・インデックスの先頭は0である
・始点に指定されたインデックスの要素についてはスライスに含まれる
・終点で指定したインデックスの1つ前の要素までがスライスに含まれる

print(TestList[1:3])
#「2」「3」が出力される。
print(TestList[1:3])
#「2」「3」「4」が出力される。
print(TestList[:3])
#「1」「2」が出力される。

リストの更新、追加

基本は以下「リスト[インデックス] = 値」で更新できる。

TestList = ["a", "b", "c", "d", "e"]
TestList[0] = "A" #先頭の要素の値を上書き
print(TestList)   # ["A", "b", "c", "d", "e"]が出力される

スライスで指定した範囲の値をまとめて上書きすることも可能

TestList = ["a", "b", "c", "d", "e"]
TestList[1:3] = ["B", "C"] #インデックス1と2にそれぞれ値を代入
print(TestList)            # ["a", "B", "C", "d", "e"]が出力される

リストに要素を追加する事も可能。

TestList = ["a", "b", "c", "d", "e"]
TestList.append("f") # ひとつだけ追加する場合はappendを使う
print(TestList)      # ["a", "b", "c", "d", "e", "f"]が出力される

注意:
appendは複数要素を追加する事は出来ない。
複数要素を追加する場合は、+=でリストに連結する。

TestList = ["a", "b", "c", "d", "e"]
TestList += ["f","g"] # 複数追加する場合は+を使う
print(TestList)       # ["a", "b", "c", "d", "e", "f", "g"]が出力される

リストの要素の削除

リストから要素を削除するには「del」を使用し、 del リスト[インデックス] と記述する。

TestList = ["a", "b", "c", "d", "e"]
del TestList[3:] #インデックス3以降の要素を削除
print(TestList)  # ["a","b", "c"]が出力される

削除の範囲をスライスで指定する事も可能。

TestList = ["a", "b", "c", "d", "e"]
del TestList[1:3] #インデックス1~2までの要素を削除
print(TestList)   # ["a","d","e"]が出力される

リストの注意点

リストの値をそのまま他の変数に代入し、代入した変数に別の値を上書きした場合、
もともとの変数の値にもその変更が適応される
これ大事ですねえ。
知らないと絶対バグらせてた。

TestList = ["a", "b", "c"]
TestList_copy = TestList   # TestList_copyにTestListの値を代入する
TestList_copy[0] = "A" # TestList_copyの先頭の値を上書きする
print(TestList_copy)   # ["A", "b", "c"]と出力される
print(TestList)        # TestListの値も["A", "b", "c"]に変更される

対処は格納の仕方があり。

TestList_copy = TestList[:]

または

TestList_copy = list(TestList)

のいずれかで代入すると、元のリストは更新されない。

TestList = ["a", "b", "c"]
TestList_copy = alphabet[:]
TestList_copy[0] = "A"
print(TestList_copy)  # ["A", "b", "c"]と出力される
print(TestList_copy)  # 変更が適用されず、["a", "b", "c"]と出力される
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0