Python 切片操作符 [], [:], [::] 和 Python 负数索引值
1. Python 负数索引值
Python 列表第一个索引是 0
,第二个索引是 1
,依此类推。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Yongqiang Cheng
list = ['cheng', 'yong', 'qiang', 'forever', 'strong']
print(list[0])
print(list[1])
print(list[2])
/home/yongqiang/miniconda3/bin/python /home/yongqiang/PycharmProjects/decision_tree_classifier/sample.py
cheng
yong
qiang
Process finished with exit code 0
Python 列表索引可以从尾部开始,最后一个元素的索引为 -1
,往前一位为 -2
,以此类推。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Yongqiang Cheng
list = ['cheng', 'yong', 'qiang', 'forever', 'strong']
print(list[-1])
print(list[-2])
print(list[-3])
/home/yongqiang/miniconda3/bin/python /home/yongqiang/PycharmProjects/decision_tree_classifier/sample.py
strong
forever
qiang
Process finished with exit code 0
正数索引值截取
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Yongqiang Cheng
nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(nums[2:7])
/home/yongqiang/miniconda3/bin/python /home/yongqiang/PycharmProjects/decision_tree_classifier/sample.py
[30, 40, 50, 60, 70]
Process finished with exit code 0
负数索引值截取
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Yongqiang Cheng
nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print("nums[2:7]:", nums[2:7])
print("nums[1]:", nums[1])
print("nums[-2]:", nums[-2])
# 从第二个开始 (包含) 截取到倒数第二个 (不包含)
print("nums[1:-2]:", nums[1:-2])
print("nums[1:]:", nums[1:])
print("nums[:-2]:", nums[:-2])
/home/yongqiang/miniconda3/bin/python /home/yongqiang/PycharmProjects/decision_tree_classifier/sample.py
nums[2:7]: [30, 40, 50, 60, 70]
nums[1]: 20
nums[-2]: 80
nums[1:-2]: [20, 30, 40, 50, 60, 70]
nums[1:]: [20, 30, 40, 50, 60, 70, 80, 90]
nums[:-2]: [10, 20, 30, 40, 50, 60, 70]
Process finished with exit code 0
2. []
, [:]
, [::]
[]
:访问序列中的一个元素,例如 str_list[3]
表示访问 str_list
序列中的第四个元素,index = 3
。
[:]
:访问序列中的一段元素,例如 str_list[1:4]
表示访问 str_list
序列中的第二到第四个元素 (str_list[1]
,str_list[2]
,str_list[3]
),不包含 str_list[4]
元素。
如果没有提供索引值,则默认从 0
开始。str_list[:4]
表示访问这个序列的第一到第四个元素 (不包含 str_list[4]
元素),str_list[4:]
表示访问第五到最后一个元素。
[::-1]
:翻转序列的元素,例如 str_list[::-1]
表示翻转 str_list
序列中的元素。
[::2]
:每隔一个元素取一个。
list[:-1]
表示从第 0
位开始直到最后一位,list[::-1]
表示倒序,从最后一位到第 0
位。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import sys
import cv2
import numpy as np
import matplotlib.pyplot as plt
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
current_directory = os.path.dirname(os.path.abspath(__file__))
print(16 * "++--")
print("current_directory:", current_directory)
print(16 * "++--")
str_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
print("str_list:", str_list)
print("str_list[3]:", str_list[3])
print("str_list[1:4]:", str_list[1:4])
print("str_list[:4]:", str_list[:4])
print("str_list[4:]:", str_list[4:])
print("str_list[::-1]:", str_list[::-1])
print("str_list[::2]:", str_list[::2])
/usr/bin/python3.5 /home/strong/sunergy_moonergy/object_counter/yongqiang.py
++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--
current_directory: /home/strong/sunergy_moonergy/object_counter
++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--
str_list: ['A', 'B', 'C', 'D', 'E', 'F', 'G']
str_list[3]: D
str_list[1:4]: ['B', 'C', 'D']
str_list[:4]: ['A', 'B', 'C', 'D']
str_list[4:]: ['E', 'F', 'G']
str_list[::-1]: ['G', 'F', 'E', 'D', 'C', 'B', 'A']
str_list[::2]: ['A', 'C', 'E', 'G']
Process finished with exit code 0
切片操作符在 Python 中的原型是 [start:stop:step]
,[开始索引:结束索引:步长值]。
开始索引:从 0
开始。序列从左向右方向中,第一个值的索引为 0
,最后一个为 -1
。
结束索引:切片操作符将取到该索引为止,不包含该索引的值。
步长值:默认是一个接着一个切取。如果为 2
,则表示进行隔一取一操作。步长值为正时表示从左向右取。如果为负,则表示从右向左取。步长值不能为 0
。
[:]
就是原样复制数据。
Microsoft Windows [版本 6.1.7601]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。
C:\Users\foreverstrong>python
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> name_string = "yongqiang"
>>>
>>> name_string
'yongqiang'
>>>
>>> name_string[::-1]
'gnaiqgnoy'
>>>
>>> name_string[::-2]
'gaqny'
>>>
>>> name_string[::-3]
'gin'
>>>
>>> name_string[::3]
'yga'
>>>
>>> name_string[::2]
'ynqag'
>>>
>>> name_string[::1]
'yongqiang'
>>>
>>> exit()
C:\Users\foreverstrong>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# yongqiang cheng
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import sys
import cv2
import numpy as np
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
current_directory = os.path.dirname(os.path.abspath(__file__))
print(16 * "++--")
print("current_directory:", current_directory)
print(16 * "++--")
str_data = 'abcdefg'
print("str_data[3]:", str_data[3])
print("str_data[3:5]:", str_data[3:5])
print("str_data[:5]:", str_data[:5])
print("str_data[3:]:", str_data[3:])
print("str_data[::2]:", str_data[::2])
print("str_data[::-1]:", str_data[::-1])
print("str_data[-1]:", str_data[-1])
print("str_data[-2]:", str_data[-2])
print("str_data[-5:-2]:", str_data[-5:-2])
print("str_data[-2:-5]:", str_data[-2:-5])
/usr/bin/python3.5 /home/strong/sunergy_moonergy/object_counter/yongqiang.py
++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--
current_directory: /home/strong/sunergy_moonergy/object_counter
++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--
str_data[3]: d
str_data[3:5]: de
str_data[:5]: abcde
str_data[3:]: defg
str_data[::2]: aceg
str_data[::-1]: gfedcba
str_data[-1]: g
str_data[-2]: f
str_data[-5:-2]: cde
str_data[-2:-5]:
Process finished with exit code 0
3. [:, :, ::-1]
[:, :, ::-1]
中括号中有两个逗号,四个冒号。
第一个冒号取遍图像的所有行数。
第二个冒号取遍图像的所有列数。
第三个和第四个冒号取遍图像的所有通道数,-1
是反向取值。
Color image loaded by OpenCV is in BGR mode.
执行 image[:, :, ::-1]
后行列不变,通道数方向,由 B、G、R 更改为 R、G、B。
Color image loaded by OpenCV is in BGR mode.
第一通道是 B。
第二通道是 G。
第三通道是 R。
Img[:, :, 2]
代表 R 通道,也就是红色分量图像。
Img[:, :, 1]
代表 G 通道,也就是绿色分量图像。
Img[:, :, 0]
代表 B 通道,也就是蓝色分量图像。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import sys
import cv2
import numpy as np
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
current_directory = os.path.dirname(os.path.abspath(__file__))
print(16 * "++--")
print("current_directory:", current_directory)
print(16 * "++--")
a = np.arange(27).reshape(3, 3, 3)
print(a)
'''
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]]
'''
print(16 * "++--")
b = a[:, :, ::-1]
print(b)
'''
[[[ 2 1 0]
[ 5 4 3]
[ 8 7 6]]
[[11 10 9]
[14 13 12]
[17 16 15]]
[[20 19 18]
[23 22 21]
[26 25 24]]]
'''
/usr/bin/python2.7 /home/strong/sunergy_moonergy/object_counter/yongqiang.py
++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--
current_directory: /home/strong/sunergy_moonergy/object_counter
++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]]
++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--
[[[ 2 1 0]
[ 5 4 3]
[ 8 7 6]]
[[11 10 9]
[14 13 12]
[17 16 15]]
[[20 19 18]
[23 22 21]
[26 25 24]]]
Process finished with exit code 0
(pt-1.4_py-3.6) yongqiang@yongqiang:~$ python
Python 3.6.10 |Anaconda, Inc.| (default, May 8 2020, 02:54:21)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>>
>>> data = np.arange(36).reshape(3, 4, 3)
>>> data
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]],
[[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21, 22, 23]],
[[24, 25, 26],
[27, 28, 29],
[30, 31, 32],
[33, 34, 35]]])
>>>
>>> data[:, :, ::-1]
array([[[ 2, 1, 0],
[ 5, 4, 3],
[ 8, 7, 6],
[11, 10, 9]],
[[14, 13, 12],
[17, 16, 15],
[20, 19, 18],
[23, 22, 21]],
[[26, 25, 24],
[29, 28, 27],
[32, 31, 30],
[35, 34, 33]]])
>>>
>>> data[:, :, 2]
array([[ 2, 5, 8, 11],
[14, 17, 20, 23],
[26, 29, 32, 35]])
>>> data[:, :, 2].shape
(3, 4)
>>>
>>> data[:, :, 1]
array([[ 1, 4, 7, 10],
[13, 16, 19, 22],
[25, 28, 31, 34]])
>>> data[:, :, 1].shape
(3, 4)
>>>
>>> data[:, :, 0]
array([[ 0, 3, 6, 9],
[12, 15, 18, 21],
[24, 27, 30, 33]])
>>> data[:, :, 0].shape
(3, 4)
>>> exit()
(pt-1.4_py-3.6) yongqiang@yongqiang:~$
4. [:, 0::2]
and [:, 1::2]
(pt-1.4_py-3.6) yongqiang@yongqiang:~$ python
Python 3.6.10 |Anaconda, Inc.| (default, May 8 2020, 02:54:21)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>>
>>> data = np.arange(24).reshape(2, 3, 4)
>>> data
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
>>>
>>> data[:, 0::2]
array([[[ 0, 1, 2, 3],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[20, 21, 22, 23]]])
>>> data[:, 0::2].shape
(2, 2, 4)
>>>
>>> data[:, 1::2]
array([[[ 4, 5, 6, 7]],
[[16, 17, 18, 19]]])
>>> data[:, 1::2].shape
(2, 1, 4)
>>>
>>> exit()
(pt-1.4_py-3.6) yongqiang@yongqiang:~$
(pt-1.4_py-3.6) yongqiang@yongqiang:~$ python
Python 3.6.10 |Anaconda, Inc.| (default, May 8 2020, 02:54:21)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>>
>>> data = np.arange(12).reshape(2, 6)
>>> data
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])
>>>
>>> data[:, 0::2]
array([[ 0, 2, 4],
[ 6, 8, 10]])
>>> data[:, 0::2].shape
(2, 3)
>>>
>>> data[:, 1::2]
array([[ 1, 3, 5],
[ 7, 9, 11]])
>>> data[:, 1::2].shape
(2, 3)
>>> exit()
(pt-1.4_py-3.6) yongqiang@yongqiang:~$
5. [:, 0]
and [:, -1]
>>> data = np.arange(12).reshape(4, 1, 3)
>>> data
array([[[ 0, 1, 2]],
[[ 3, 4, 5]],
[[ 6, 7, 8]],
[[ 9, 10, 11]]])
>>>
>>> data.shape
(4, 1, 3)
>>>
>>> data[:, 0].shape
(4, 3)
>>> data[:, 0]
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
>>>
>>> data[:, -1].shape
(4, 3)
>>> data[:, -1]
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
>>>
>>> data = np.arange(36).reshape(4, 3, 3)
>>> data
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]],
[[27, 28, 29],
[30, 31, 32],
[33, 34, 35]]])
>>>
>>> data[:, 0].shape
(4, 3)
>>> data[:, 0]
array([[ 0, 1, 2],
[ 9, 10, 11],
[18, 19, 20],
[27, 28, 29]])
>>>
>>> data[:, 1].shape
(4, 3)
>>> data[:, 1]
array([[ 3, 4, 5],
[12, 13, 14],
[21, 22, 23],
[30, 31, 32]])
>>>
>>> data[:, 2].shape
(4, 3)
>>> data[:, 2]
array([[ 6, 7, 8],
[15, 16, 17],
[24, 25, 26],
[33, 34, 35]])
>>>
>>> data[:, -1].shape
(4, 3)
>>> data[:, -1]
array([[ 6, 7, 8],
[15, 16, 17],
[24, 25, 26],
[33, 34, 35]])
>>>
6. [:, 0:1]
- [:, 0:2]
- [:, 0:3]
>>> data = np.arange(36).reshape(4, 3, 3)
>>> data
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]],
[[27, 28, 29],
[30, 31, 32],
[33, 34, 35]]])
>>>
>>> data[:, 0:1].shape
(4, 1, 3)
>>> data[:, 0:1]
array([[[ 0, 1, 2]],
[[ 9, 10, 11]],
[[18, 19, 20]],
[[27, 28, 29]]])
>>>
>>> data[:, 0:2].shape
(4, 2, 3)
>>> data[:, 0:2]
array([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 9, 10, 11],
[12, 13, 14]],
[[18, 19, 20],
[21, 22, 23]],
[[27, 28, 29],
[30, 31, 32]]])
>>>
>>> data[:, 0:3].shape
(4, 3, 3)
>>> data[:, 0:3]
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]],
[[27, 28, 29],
[30, 31, 32],
[33, 34, 35]]])
>>>
References
[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/