about 3 years ago

Know How to Slice Sequences

在講 slicing
[start:end)

a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

a[:]      # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

a[:5]     # ['a', 'b', 'c', 'd', 'e']

a[:-1]    # ['a', 'b', 'c', 'd', 'e', 'f', 'g']

a[4:]     # ['e', 'f', 'g', 'h']

a[-3:]    # ['f', 'g', 'h']

a[2:5]    # ['c', 'd', 'e']

a[2:-1]   # ['c', 'd', 'e', 'f', 'g']

a[-3:-1]  #  ['f', 'g']

slicing 的結果是新的 object,所以上面的 a[:] 其實等同複製一整個 list。

slicing 就算索引值超過 list 長度也沒關係

first_twenty_items = a[:20]
last_twenty_items = a[-20:]

# IndexError

a[0]

對 slice 賦值的情況

a = [0, 1, 2]
a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]

相關

Python 慣用語 - 7 負數索引值

← Effective Python 心得筆記: Item 4 Effective Python 心得筆記: Item 6 →
 
comments powered by Disqus