人工智能必备数学知识学习笔记2:向量

 

 

 

 

 

 

 代码实现向量:

1. pycharm中创建项目LinearAlgebra

2.在该项目中创建Python Package的名字叫 playLA

3.创建Vector.py文件

 4.在Vector.py中编写

 1 #向量类
 2 class Vector:
 3 
 4     def __init__(self,lst):
 5         self.__values = lst#将数组赋值给向量类中
 6 
 7     #取向量的index个元素
 8     def __getitem__(self, index):
 9         return self.__values[index]
10 
11     #返回向量的长度(有多少个元素)
12     def __len__(self):
13         return len(self.__values)
14 
15     # 向量展示(系统调用)
16     def __repr__(self):
17         return "Vector({})".format(self.__values)
18 
19     # 向量展示(用户调用)
20     def __str__(self):
21         return "({})".format(", ".join(str(e) for e in self.__values))#通过遍历 self.__values 将e转成字符串通过逗号加空格来链接放入大括号中
22 
23 # u = Vector([5,2])
24 # print(u)

5.在终端测试分别调用向量展示的方法__repr__(系统调用)与__str__(用户调用)

 6.在工程下(playLA包外)创建测试Python文件 main_vector

 

 7.在main_vector中调用Vector的类

1 from playLA.Vector import Vector
2 
3 if __name__ == "__main__":
4 
5     vec = Vector([5,2])
6     print(vec)
7     print(len(vec))#打印向量的维度
8     print("vec[0] = {}, vec[1] = {}".format(vec[0],vec[1]))

 8.运行mian_vector结果为:

原文地址:https://www.cnblogs.com/liuxiaoming123/p/13377561.html