1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

python スライスの仕組み

Last updated at Posted at 2022-12-11

スライスとは?

スライス
⇒シーケンスなオブジェクトの要素を指定して、新たなオブジェクトを生成すること。
シーケンス[始まり:終わり:ストライド]というような形で指定する。
特殊メソッドの__getiteam__と__setiteam__を実装したクラスをスライスすることができる。

numbers = [0, 1, 2, 3, 4, 5, 6]
print(numbers[:4])
print(numbers[0:3])
print(numbers[-1:0:-1])
print(numbers[0:7:2])

>>> 
[0, 1, 2, 3]
[0, 1, 2]
[6, 5, 4, 3, 2, 1]
[0, 2, 4, 6]

特殊メソッドとは

各種演算子、組み込み関数などの操作を独自に定義したクラスを利用できるようにするための仕組みのこと。init__や__str,__repr__など。

__getiteam__とは、クラスにキーを指定して(辞書型のような)アクセスを可能にさせる特殊メソッド。

class ExamGetitem(object):
    
    def __getitem__(self, time):
        if time == 15:
            return 'おやつの時間ですよ'
        elif time == 12:
            return 'お昼の時間ですよ'
        elif time == 18:
            return '夕食の時間ですよ'
        elif time == 6:
            return '朝ごはんの時間ですよ'
        else:
            return 'おなかはいっぱいです'

A = exam_getitem()
print('6時:',A[6])
print('12時:',A[12])
print('15時:',A[15])
print('18時:',A[18])
print('19時:', A[19])

>>>
6: 朝ごはんの時間ですよ
12: お昼の時間ですよ
15: おやつの時間ですよ
18: 夕食の時間ですよ
19: おなかはいっぱいです

スライスの注意点

スライスを指定する際、存在しないインデックスを範囲に含めて指定することはできるが、存在しないインデックスの値を取り出すことはできない。

exam_list = [0, 1, 2, 3, 4, 5, 6,7, 8, 9, 10]

len_list = len(exam_list)
print(len_list)
print(exam_list[100:])
print(exam_list[:-100])
print(exam_list[-0:])
print(exam_list[-12])

>>>
11
[]
[]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    print(exam_list[100])
IndexError: list index out of range

スライスで生成したオブジェクトは、元のオブジェクトとは異なる

exam_list = [0, 1, 2, 3, 4, 5, 6,7, 8, 9, 10]

copy_exam_list = exam_list[:]

assert exam_list is copy_exam_list

>>>
assert exam_list is copy_exam_list
AssertionError

スライスに代入を行う場合、数が等しくなくてもよい

exam_list = [0, 1, 2, 3, 4, 5, 6,7, 8, 9, 10]
print(exam_list)
print('*' * 30)
exam_list[2:8] = 'A', 'B'
print(exam_list)

>>>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
******************************
[0, 1, 'A', 'B', 8, 9, 10]
1
1
1

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?