Python配列スライスの使い方の詳細

19884 ワード

Pythonの使用中にスライスがよく使われるので、スライスの使い方をまとめてみました.
ASCII art diagram、Pythonスライスの理解を助ける:
 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1
>>> a = ['P','y','t','h','o','n']
>>> a[0:1]
 ['P']
>>> a[1:3]
 ['y','t']
 
>>> a[-2:-1]
 ['o']
>>> a[:-1]
 ['P', 'y', 't', 'h', 'o']

ステップ長stepパラメータなしのスライスで、ステップ長のデフォルトは1です.
a[start:stop]  #    stop-1   stop   
a[start:]      #    start       
a[:stop]       #     stop          
a[:]           #     a

ステップ長stepパラメータ付きスライス:
a[start:stop:step] 

索引が複数のスライス:
a = ['P','y','t','h','o','n']
a[-1]    #             -->'n'
a[-2:]   #             -->['o', 'n']
a[:-2]   #                    -->['P', 'y', 't', 'h']

ステップ長が複数のスライス:
a[::-1]    #             -->['n', 'o', 'h', 't', 'y', 'P']
a[1::-1]   #                -->['y', 'P']
a[:-3:-1]  #             -->['n', 'o']
a[-3::-1]  #                   -->['h', 't', 'y', 'P']

slice()オブジェクトとの関係:次の2つの使い方は同じです.
a[start:stop:step] 
a[slice(start, stop, step)]

インデックス(index)との違い:ASCII art diagramは両者の違いを理解するのに役立ちます.
                +---+---+---+---+---+---+
                | P | y | t | h | o | n |
                +---+---+---+---+---+---+
Slice position: 0   1   2   3   4   5   6
Index position:   0   1   2   3   4   5
>>> a = ['P','y','t','h','o','n']
#   
>>> a[0]
 'P'
>>> a[5]
 'n'
#   
>>> a[0:1]
 ['P']
>>> a[0:2]
 ['P','y']

もう1つの理解方法:
ステップ長:

>>> seq[:]                # [seq[0],   seq[1],          ..., seq[-1]    ]
>>> seq[low:]             # [seq[low], seq[low+1],      ..., seq[-1]    ]
>>> seq[:high]            # [seq[0],   seq[1],          ..., seq[high-1]]
>>> seq[low:high]         # [seq[low], seq[low+1],      ..., seq[high-1]]
>>> seq[::stride]         # [seq[0],   seq[stride],     ..., seq[-1]    ]
>>> seq[low::stride]      # [seq[low], seq[low+stride], ..., seq[-1]    ]
>>> seq[:high:stride]     # [seq[0],   seq[stride],     ..., seq[high-1]]
>>> seq[low:high:stride]  # [seq[low], seq[low+stride], ..., seq[high-1]]

ステップ長:
>>> seq[::-stride]        # [seq[-1],   seq[-1-stride],   ..., seq[0]    ]
>>> seq[high::-stride]    # [seq[high], seq[high-stride], ..., seq[0]    ]
>>> seq[:low:-stride]     # [seq[-1],   seq[-1-stride],   ..., seq[low+1]]
>>> seq[high:low:-stride] # [seq[high], seq[high-stride], ..., seq[low+1]]

参照先:https://stackoverflow.com/questions/509211/understanding-slice-notation https://www.w3schools.com/python/ref_func_slice.asp https://www.geeksforgeeks.org/python-slice-function/