赞
踩
这个函数在numpy中
函数形式:tile (A, reps)
重复A的各个维度,reps是重复的次数
from numpy import tile
Array = [1,2,3]
y = tile(Array,2)
输出为:
[1 2 3 1 2 3]
y = tile(Array,(2,2))
这个相当于先得到 [1 2 3 1 2 3],再重复
输出为:
[[1 2 3 1 2 3]
[1 2 3 1 2 3]]
y = tile(Array,(2,2,2))
输出为:
[[[1 2 3 1 2 3]
[1 2 3 1 2 3]]
[[1 2 3 1 2 3]
[1 2 3 1 2 3]]]
张量可以和之前学的矢量和矩阵相联系。
下面是一个3阶张量:
[
[[9,1,8],[6,7,5],[3,4,2]],
[[2,9,1],[8,6,7],[5,3,4]],
[[1,5,9],[7,2,6],[4,8,3]]
]
中间的每一行都是一个矩阵(2阶张量)
另外,3阶张量又叫”空间矩阵“或者”三维矩阵“,例如:
n表示的是张量的第n+1维元素的个数。
在矩阵中
Matrix = np.matrix([[1,2,3,4],
[2,3,4,5],
[1,4,5,6]])
Matrix.shape[0] = 3
Matrix.shape[1] = 4
这两个运算都在numpy中。对于两个矩阵
对某个维度求和。
Matrix = np.matrix([[1,2,3,4],
[2,3,4,5],
[1,4,5,6]])
Sum_0 = Matrix.sum(axis=0)
输出为:
[[ 4 9 12 15]]
Matrix = np.matrix([[1,2,3,4],
[2,3,4,5],
[1,4,5,6]])
Sum_1 = Matrix.sum(axis=1)
输出为:
[[10]
[14]
[16]]
将一个数组有小到大排序,并提取每个元素对应的索引(index)。
Array = np.array([5,4,3,2,1])
Index = Array.argsort()
输出为:
[4 3 2 1 0]
argsort()也可以作用到矩阵上。
Matrix = np.matrix([[1,2,3,4],
[2,3,4,5],
[1,4,5,6]])
Index = Matrix.argsort()
输出为:
[[0 1 2 3]
[0 1 2 3]
[0 1 2 3]]
可见argsort()是以数组为单位对矩阵进行处理的。
函数形式:get(key, default)
对于一个字典dict,调用get()。如果key存在,则返回其对应的value;如果不存在,则返回default的值。
Dict = {
'name':'Francis','age':19}
print(Dict.get('name','No such key!'))
print(Dict.get('gender','No such key!'))
输出为:
Francis
No such key!
dict.items()可以生成一个以(key, value)为元素的列表。
dict.iteritems()与items()类似,但生成的是一个迭代器。迭代器在遍历时很方便。
但注意iteritems()在python 3中已经被废除,它可以用for循环和items()实现。
Dict = {
'name':'Francis','age':19,'gender':'male'}
List1 = Dict.items()
print(List1)
输出为:
dict_items([(‘name’, ‘Francis’), (‘age’, 19), (‘gender’, ‘male’)])
从小到大排列列表。
函数形式:sorted(list, key, reverse)
List = ['Francis','Jack','Marry','Smithson']
y = sorted(List,key=len,reverse=False) #注意这里用的是key=len,而不是len()
print(y)
输出为:
[‘Jack’, ‘Marry’, ‘Francis’, ‘Smithson’]
operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号)。
List = ['Francis','Jack','Marry','Smithson']
function = operator.itemgetter(1)
print(function(List))
输出为:
Jack
from numpy import *
import operator
def creatDataSet():
group = array([[1.0,1.1
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。