Python切片截取

Python切片截取

1. List的截取

對於一維List的截取:

L = [1,2,3,4,5,6,7,8,9]
print (L[:]) #返回整個list
#[1, 2, 3, 4, 5, 6, 7, 8, 9]
print (L[1:5]) #返回下標1-5組成的新list,包括1,不包括5
#[2, 3, 4, 5]
print (L[:5]) #返回下標從0-5組成的新list,包括0,不包括5
#[1, 2, 3, 4, 5]
print (L[1:]) #返回小標1-末尾組成的新list,包括1
#[2, 3, 4, 5, 6, 7, 8, 9]
print (L[::1]) #從左到右按照步長爲1截取
#[1, 2, 3, 4, 5, 6, 7, 8, 9]
print (L[::2]) #從左到右按照步長爲2截取
#[1, 3, 5, 7, 9]
print (L[::-2]) #從右到左按照步長爲2截取
#[9, 7, 5, 3, 1]

對於二維List的截取:

L = [[1,2,3,4,5],[6,7,8,9,10]] #將list中的list當成元素
print (L[1:2])
#[[6, 7, 8, 9, 10]]
#print (L[1:2,1:2]) #報錯

2. numpy.array的切片

import numpy as np
foo = np.array([[1,2,3],
                [4,5,6],
                [7,8,9]])
print (foo[1:2]) #截取行維度的第一行到第二行,包括第一行,不包括第二行
#[[4 5 6]]
print (foo[1:2,1:2]) #截取行維度的第一行和列維度的第一列
#[[5]]
print (foo[::2]) #行維度按照從上到下步長爲2截取
#[[1 2 3]
# [7 8 9]]
print (foo[::2,::-1]) #行維度按照從上到下步長爲2截取並且列維度按照從右到左步長爲1截取
#[[3 2 1]
# [9 8 7]]
print (foo[::2,::2]) #行維度按照從上到下步長爲2截取並且列維度按照從左到右步長爲2截取
#[[1 3]
# [7 9]]

3. tensorflow.Tensor的切片

import tensorflow as tf
sess = tf.Session()
foo = tf.constant([1,2,3,4,5,6])
print(foo[2:4].eval(session=sess)) #截取下標2-4的元素,包括2,不包括4
#[3 4]

tensorflow按照步長截取的例子:

import tensorflow as tf
sess = tf.Session()
foo = tf.constant([[1,2,3],[4,5,6],[7,8,9]])  
print(foo[::2,::-1].eval(session=sess)) #方法同numpy的截取
#[[3 2 1]
# [9 8 7]]

3. 總結

python的切片操作都是大同小異的,掌握好切片操作會讓我們更簡單的處理數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章