在神经网络开发中,经常要操作多维列表,常见的有X[:,0]、X[:,1]、X[:,:,0]、X[:,:,1]、X[:,m:n]、X[:,:,m:n]和X[: : -1]
X[:,0];是取二维数组中第一维的所有数据
X[:,1]是取二维数组中第二维的所有数据
X[:,m:n]是取二维数组中第m维到第n-1维的所有数据
X[:,:,0]是取三维矩阵中第一维的所有数据
X[:,:,1]是取三维矩阵中第二维的所有数据
X[:,:,m:n]是取三维矩阵中第m维到第n-1维的所有数据
实例:
#!usr/bin/env python
#encoding:utf-8
from __future__ import division
import numpy as np
def simple_test():
'''
简单的小实验
'''
data_list=[[1,2,3],[1,2,1],[3,4,5],[4,5,6],[5,6,7],[6,7,8],[6,7,9],[0,4,7],[4,6,0],[2,9,1],[5,8,7],[9,7,8],[3,7,9]]
# data_list.toarray()
data_list=np.array(data_list)
print 'X[:,0]结果输出为:'
print data_list[:,0]
print 'X[:,1]结果输出为:'
print data_list[:,1]
print 'X[:,m:n]结果输出为:'
print data_list[:,0:1]
data_list=[[[1,2],[1,0],[3,4],[7,9],[4,0]],[[1,4],[1,5],[3,6],[8,9],[5,0]],[[8,2],[1,8],[3,5],[7,3],[4,6]],
[[1,1],[1,2],[3,5],[7,6],[7,8]],[[9,2],[1,3],[3,5],[7,67],[4,4]],[[8,2],[1,9],[3,43],[7,3],[43,0]],
[[1,22],[1,2],[3,42],[7,29],[4,20]],[[1,5],[1,20],[3,24],[17,9],[4,10]],[[11,2],[1,110],[3,14],[7,4],[4,2]]]
data_list=np.array(data_list)
print 'X[:,:,0]结果输出为:'
print data_list[:,:,0]
print 'X[:,:,1]结果输出为:'
print data_list[:,:,1]
print 'X[:,:,m:n]结果输出为:'
print data_list[:,:,0:1]
if __name__ == '__main__':
simple_test()
输出如下:
X[:,0]结果输出为:
[1 1 3 4 5 6 6 0 4 2 5 9 3]
X[:,1]结果输出为:
[2 2 4 5 6 7 7 4 6 9 8 7 7]
X[:,m:n]结果输出为:
[[1]
[1]
[3]
[4]
[5]
[6]
[6]
[0]
[4]
[2]
[5]
[9]
[3]]
X[:,:,0]结果输出为:
[[ 1 1 3 7 4]
[ 1 1 3 8 5]
[ 8 1 3 7 4]
[ 1 1 3 7 7]
[ 9 1 3 7 4]
[ 8 1 3 7 43]
[ 1 1 3 7 4]
[ 1 1 3 17 4]
[11 1 3 7 4]]
X[:,:,1]结果输出为:
[[ 2 0 4 9 0]
[ 4 5 6 9 0]
[ 2 8 5 3 6]
[ 1 2 5 6 8]
[ 2 3 5 67 4]
[ 2 9 43 3 0]
[ 22 2 42 29 20]
[ 5 20 24 9 10]
[ 2 110 14 4 2]]
X[:,:,m:n]结果输出为:
[[[ 1]
[ 1]
[ 3]
[ 7]
[ 4]]
[[ 1]
[ 1]
[ 3]
[ 8]
[ 5]]
[[ 8]
[ 1]
[ 3]
[ 7]
[ 4]]
[[ 1]
[ 1]
[ 3]
[ 7]
[ 7]]
[[ 9]
[ 1]
[ 3]
[ 7]
[ 4]]
[[ 8]
[ 1]
[ 3]
[ 7]
[43]]
[[ 1]
[ 1]
[ 3]
[ 7]
[ 4]]
[[ 1]
[ 1]
[ 3]
[17]
[ 4]]
[[11]
[ 1]
[ 3]
[ 7]
[ 4]]]
X[: : m]代表了[开始:结束:步进],步进默认为 1
>>>string = 'python'
>>>string[::1] # 步进为1
'python'
>>> string[::2] # 步进为2, [0, 0+2, 0+2+2...]
'pto'
X[: : -1]将列表或字符反转在操作
>>> list = [1,2,3,4,5,6,7,7,8]
>>> list[::-1][:3]
[8, 7, 7]
网友评论