python学习笔记

main入口

if __name__ == '__main__':
    print("hello")


内置数据结构


元组

<span style="font-size:18px;">tuple = ("apple", "banana", "grape", "orange")
#tuple[0] = "a"#'tuple' object does not support item assignment
t = ("apple",)
t = ()
print tuple[-1]
print tuple[-2]
#print t[0]</span>

输出

<span style="font-size:18px;">orange
grape</span>

<span style="font-size:18px;">tuple = ("apple", "banana", "grape", "orange")
print tuple[-1]
print tuple[-2]
tuple2 = tuple[1:3]
tuple3 = tuple[0:-2]
tuple4 = tuple[2:-2]
print tuple2
print tuple3
print tuple4

fruit1 = ("apple", "banana")
fruit2 = ("grape", "orange")
tuple = (fruit1, fruit2)
print tuple
print "tuple[0][1] =",tuple[0][1]
print "tuple[1][1] =",tuple[1][1]
#print tuple[1][2]

#打包
tuple = ("apple", "banana", "grape", "orange")
#解包
a, b, c, d = tuple
print a, b, c, d
</span>
输出
<span style="font-size:18px;">orange
grape
('banana', 'grape')
('apple', 'banana')
()
(('apple', 'banana'), ('grape', 'orange'))
tuple[0][1] = banana
tuple[1][1] = orange
apple banana grape orange</span>

元组遍历

<span style="font-size:18px;">#使用range()循环遍历
tuple = (("apple", "banana"),("grape", "orange"),("watermelon",),("grapefruit",))
for i in range(len(tuple)):
    print "tuple[%d] :" % i, "" ,
    for j in range(len(tuple[i])):
        print tuple[i][j], "" ,
    print

#使用map()循环遍历
k = 0
for a in map(None,tuple):
    print "tuple[%d] :" % k, "" ,
    for x in a:
        print x, "" , 
    print
    k += 1</span>

输出

<span style="font-size:18px;">tuple[0] :  apple  banana 
tuple[1] :  grape  orange 
tuple[2] :  watermelon 
tuple[3] :  grapefruit 
tuple[0] :  apple  banana 
tuple[1] :  grape  orange 
tuple[2] :  watermelon 
tuple[3] :  grapefruit </span>


列表

<span style="font-size:18px;">list = ["apple", "banana", "grape", "orange"]
print list
print list[2]
list.append("watermelon")
list.insert(1, "grapefruit")
print list
list.remove("grape")
print list
#list.remove("a")
print list.pop()
print list

list = ["apple", "banana", "grape", "orange"]
print list[-2]
print list[1:3]
print list[-3:-1]
list = [["apple", "banana"],["grape", "orange"],["watermelon"],["grapefruit"]]
for i in range(len(list)):
    print "list[%d] :" % i, "" ,
    for j in range(len(list[i])):
        print list[i][j], "" ,
    print</span>

输出

<span style="font-size:18px;">['apple', 'banana', 'grape', 'orange']
grape
['apple', 'grapefruit', 'banana', 'grape', 'orange', 'watermelon']
['apple', 'grapefruit', 'banana', 'orange', 'watermelon']
watermelon
['apple', 'grapefruit', 'banana', 'orange']
grape
['banana', 'grape']
['banana', 'grape']
list[0] :  apple  banana 
list[1] :  grape  orange 
list[2] :  watermelon 
list[3] :  grapefruit </span>


关于list.pop

>>> list = ["apple", "banana", "grape", "orange"]
>>> list.pop(2)
'grape'
>>> list
['apple', 'banana', 'orange']
>>> 
<span style="font-size:18px;">list = ["grape", "apple"]
list2 = ["apple", list, "orange"]             
print list
print list2

list3=[i for i in list if i not in list2]
print list3
</span>

输出

<span style="font-size:18px;">['grape', 'apple']
['apple', ['grape', 'apple'], 'orange']
['grape']</span>

<span style="font-size:18px;">list = ["apple", "grape", "grape", "orange"]
list.remove("grape")
print list

list = ["apple", "banana", "grape", "orange"]
print list.index("grape")
print list.index("orange")
print "orange" in list

list1 = ["apple", "banana"]
list2 = ["grape", "orange"]
list1.extend(list2)
print list1
list3 = ["watermelon"]
list1 = list1 + list3
print list1
list1 += ["grapefruit"]
print list1
list1 = ["apple", "banana"] * 2
print list1

#使用列表的sort方法排序
list = ["banana", "apple", "orange", "grape"]
list.sort()
print "Sorted list:", list
list.reverse()
print "Reversed list:", list

#使用函数sorted排序,返回一个新的列表
list = ["banana", "apple", "orange", "grape"]
for li in sorted(set(list)):
    print li, "" ,</span>

输出

<span style="font-size:18px;">['apple', 'grape', 'orange']
2
3
True
['apple', 'banana', 'grape', 'orange']
['apple', 'banana', 'grape', 'orange', 'watermelon']
['apple', 'banana', 'grape', 'orange', 'watermelon', 'grapefruit']
['apple', 'banana', 'apple', 'banana']
Sorted list: ['apple', 'banana', 'grape', 'orange']
Reversed list: ['orange', 'grape', 'banana', 'apple']
apple  banana  grape  orange </span>

字典

<span style="font-size:18px;">#使用字母作为索引
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
print dict
print dict["a"]
#使用数字作为索引
dict = {1 : "apple", 2 : "banana", 3 : "grape", 4 : "orange"}
print dict
print dict[2]
#字典的添加、删除
dict = {1 : "apple", 2 : "banana", 3 : "grape", 4 : "orange"}
del dict[1]
print dict
print dict[2]
#使用元组作为索引
dict = {}
dict[("a","p","p","l","e")] = "apple"
dict[("b","a","n","a","n","a")] = "banana"
print dict
print dict[("a","p","p","l","e")]
#匿名字典
print " %(a)s, %(b)s" % {"a":"apple", "b":"banana"}</span>

输出

<span style="font-size:18px;">{'a': 'apple', 'b': 'banana', 'o': 'orange', 'g': 'grape'}
apple
{1: 'apple', 2: 'banana', 3: 'grape', 4: 'orange'}
banana
{2: 'banana', 3: 'grape', 4: 'orange'}
banana
{('b', 'a', 'n', 'a', 'n', 'a'): 'banana', ('a', 'p', 'p', 'l', 'e'): 'apple'}
apple
 apple, banana</span>

<span style="font-size:18px;">#字典的添加、删除、修改操作
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
dict["w"] = "watermelon"
del(dict["a"])
dict["g"] = "grapefruit"
print dict.pop("b")
print dict
dict.clear()
print dict

#字典的遍历
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for k in dict:
    print "dict[%s] =" % k,dict[k]

#字典items()的使用
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"} 
#每个元素是一个key和value组成的元组,以列表的方式输出
print dict.items()

#调用items()实现字典的遍历
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for (k, v) in dict.items():
    print "dict[%s] =" % k, v

#调用iteritems()实现字典的遍历
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"} 
print dict.iteritems()
for k, v in dict.iteritems():
    print "dict[%s] =" % k, v
for (k, v) in zip(dict.iterkeys(), dict.itervalues()):
    print "dict[%s] =" % k, v
    


#使用列表、字典作为字典的值
dict = {"a" : ("apple",), "bo" : {"b" : "banana", "o" : "orange"}, "g" : ["grape","grapefruit"]}
print dict["a"]
print dict["a"][0]
print dict["bo"]
print dict["bo"]["o"]
print dict["g"]
print dict["g"][1]</span>

输出

<span style="font-size:18px;">banana
{'w': 'watermelon', 'o': 'orange', 'g': 'grapefruit'}
{}
dict[a] = apple
dict[b] = banana
dict[o] = orange
dict[g] = grape
[('a', 'apple'), ('c', 'grape'), ('b', 'banana'), ('d', 'orange')]
dict[a] = apple
dict[b] = banana
dict[o] = orange
dict[g] = grape
<dictionary-itemiterator object at 0x02659690>
dict[a] = apple
dict[c] = grape
dict[b] = banana
dict[d] = orange
dict[a] = apple
dict[c] = grape
dict[b] = banana
dict[d] = orange
('apple',)
apple
{'b': 'banana', 'o': 'orange'}
orange
['grape', 'grapefruit']
grapefruit</span>

<span style="font-size:18px;">#字典的更新
dict = {"a" : "apple", "b" : "banana"}
print dict
dict2 = {"c" : "grape", "d" : "orange"}
dict.update(dict2)
print dict</span>
输出

<span style="font-size:18px;">{'a': 'apple', 'b': 'banana'}
{'a': 'apple', 'c': 'grape', 'b': 'banana', 'd': 'orange'}
</span>

<span style="font-size:18px;">#调用sorted()排序
dict = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"} 
print dict   
#按照key排序  
print sorted(dict.items(), key=lambda d: d[0])
#按照value排序  
print sorted(dict.items(), key=lambda d: d[1])

#字典的浅拷贝
dict = {"a" : "apple", "b" : "grape"} 
dict2 = {"c" : "orange", "d" : "banana"} 
dict2 = dict.copy()
print dict2


#字典的深拷贝
import copy
dict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}} 
dict2 = copy.deepcopy(dict)
dict3 = copy.copy(dict)
dict2["b"]["g"] = "orange"
print dict
dict3["b"]["g"] = "orange"
print dict</span>
输出

<span style="font-size:18px;">{'a': 'apple', 'c': 'orange', 'b': 'grape', 'd': 'banana'}
[('a', 'apple'), ('b', 'grape'), ('c', 'orange'), ('d', 'banana')]
[('a', 'apple'), ('d', 'banana'), ('b', 'grape'), ('c', 'orange')]
{'a': 'apple', 'b': 'grape'}
{'a': 'apple', 'b': {'o': 'orange', 'g': 'grape'}}
{'a': 'apple', 'b': {'o': 'orange', 'g': 'orange'}}</span>






字符串操作

格式化输出

print "%.*s" % (4,"jcodeer")

输出jcod

<span style="font-size:18px;">#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 格式化字符串
str1 = "version"
num = 1.0
format = "%s" % str1
print format
format = "%s %d" % (str1, num)
print format

# 带精度的格式化
print "浮点型数字: %f" % 1.25   
print "浮点型数字: %.1f" % 1.25 
print "浮点型数字: %.2f" % 1.254 

# 使用字典格式化字符串
print "%(version)s: %(num).1f" % {"version": "version", "num": 2}

# 字符串对齐
word = "version3.0"
print word.center(20)
print word.center(20, "*")
print word.ljust(0)
print word.rjust(20)
print "%30s" % word</span>
输出

<span style="font-size:18px;">version
version 1
浮点型数字: 1.250000
浮点型数字: 1.2
浮点型数字: 1.25
version: 2.0
     version3.0     
*****version3.0*****
version3.0
          version3.0
                    version3.0</span>


字符转义

<span style="font-size:18px;"># -*- coding: UTF-8 -*-

# 输出转义字符
path = "hello\tworld\n"
print path
print len(path)  
path = r"hello\tworld\n" 
print path
print len(path)  


# strip()去掉转义字符
word = "\thello world\n"
print "直接输出:", word
print "strip()后输出:", word.strip()
print "lstrip()后输出:", word.lstrip()
print "rstrip()后输出:", word.rstrip()</span>

<span style="font-size:18px;">hello	world

12
hello\tworld\n
14
直接输出: 	hello world

strip()后输出: hello world
lstrip()后输出: hello world

rstrip()后输出: 	hello world</span>


字符串连接

<span style="font-size:18px;"># -*- coding: UTF-8 -*-

# 使用"+"连接字符串
str1 = "hello "
str2 = "world "
str3 = "hello "
str4 = "China "
result = str1 + str2 + str3
result += str4
print result

# 使用join()连接字符串
strs = ["hello ", "world ", "hello ", "China "]
result = "".join(strs)
print result

# 使用reduce()连接字符串
import operator
strs = ["hello ", "world ", "hello ", "China "]
result = reduce(operator.add, strs, "")
print result
</span>

输出


<span style="font-size:18px;">hello world hello China 
hello world hello China 
hello world hello China </span>


字符串的截取

<span style="font-size:18px;"># -*- coding: UTF-8 -*-

# 使用索引截取子串
word = "world"
print word[4]

# 使用split()获取子串
sentence = "Bob said: 1, 2, 3, 4"
print "使用空格取子串:", sentence.split()
print "使用逗号取子串:", sentence.split(",")
print "使用两个逗号取子串:", sentence.split(",", 2)

# 字符串连接后将分配新的空间
str1 = "a"
print id(str1)
print id(str1 + "b")

# 特殊切片截取子串
str1 = "hello world"
print word[0:3]
print str1[::2]
print str1[1::2]</span>
输出

<span style="font-size:18px;">d
使用空格取子串: ['Bob', 'said:', '1,', '2,', '3,', '4']
使用逗号取子串: ['Bob said: 1', ' 2', ' 3', ' 4']
使用两个逗号取子串: ['Bob said: 1', ' 2', ' 3, 4']
4199272
34943512
wor
hlowrd
el ol</span>



字符串反转

<span style="font-size:18px;"># -*- coding: UTF-8 -*-

# 使用list的reverse()
def reverse(s):    
    li = list(s) 
    li.reverse()
    s = "".join(li)
    return s

print reverse("hello")

# 循环输出反转的字符串
def reverse(s):
    out = ""
    li = list(s) 
    for i in range(len(li), 0, -1):
        out += "".join(li[i-1])
    return out

print reverse("hello")

# 特殊切片反转字符串
def reverse(s):
    return s[::-1]

print reverse("hello")</span>

输出

<span style="font-size:18px;">olleh
olleh
olleh</span>



字符串查找

<span style="font-size:18px;"># 查找字符串
sentence = "This is a apple."
print sentence.find("a")
sentence = "This is a apple."
print sentence.rfind("a")</span>
输出

<span style="font-size:18px;">8
10</span>



字符串替换

<span style="font-size:18px;"># 字符串的替换
centence = "hello world, hello China"
print centence.replace("hello", "hi")
print centence.replace("hello", "hi", 1)
print centence.replace("abc", "hi")
</span>
输出

<span style="font-size:18px;">hi world, hi China
hi world, hello China
hello world, hello China</span>



文件操作

创建文件

# 创建文件
context = '''hello world
hello China            
'''
f = file('hello.txt', 'w')   # 打开文件
f.write(context)             # 把字符串写入文件
f.close()                    # 关闭文件

读取文件

# 使用readline()读文件
f = open("hello.txt")
while True:
    line = f.readline()
    if line: 
        print line,
    else:
        break
f.close()

# 使用readlines()读文件
f = file('hello.txt')
lines = f.readlines()
for line in lines:   
    print line,
f.close()                   # 关闭文件 

# 使用read()读文件
f = open("hello.txt")
context = f.read() 
print context
f.close()

# read(size)
f = open("hello.txt")
context = f.read(5) 
print context
print f.tell()
context = f.read(5) 
print context
print f.tell()
f.close()

hello.txt内容如下

hello world
hello China

输出

hello world
hello China            
hello world
hello China            
hello world
hello China            

hello
5
 worl
10

写入文件

# 使用writelines()读文件
f = file("hello.txt", "w+")
li = ["hello world\n", "hello China\n"]
f.writelines(li)
f.close()    

# 追加新的内容到文件
f = file("hello.txt", "a+")
new_context = "goodbye"
f.write(new_context)
f.close()   

删除文件

import os

file("hello.txt", "w")
if os.path.exists("hello.txt"):
    os.remove("hello.txt")

目录基础知识

/表示根目录, ./表示当前路径, ../表示上一级父目录

./SRC/ 这样写表示,当前目录中的SRC文件夹; ../SRC/ 这样写表示,当前目录的上一层目录中SRC文件夹; /SRC/ 这样写表示,项目根目录(可以只磁盘根目录,也可以指项目根目录,具体根据实际情况而定)

# 使用read()、write()实现拷贝
# 创建文件hello.txt
src = file("hello.txt", "w")
li = ["hello world\n", "hello China\n"]
src.writelines(li) 
src.close()
# 把hello.txt拷贝到hello2.txt
src = file("hello.txt", "r")
dst = file("hello2.txt", "w")
dst.write(src.read())
src.close()
dst.close()


# shutil模块实现文件的拷贝
import shutil

shutil.copyfile("hello.txt","hello2.txt")
#将hello.txt移动到上一级目录
shutil.move("hello.txt","../")
#当前目录下hello2.txt不存在了,只有hello3.txt
shutil.move("hello2.txt","hello3.txt") 

文件重命名

# 修改文件名
import os
from nt import chdir

#列出当前目录的父目录下的文件
#同理os.listdir(".")列出当前目录下的文件
li = os.listdir("..")
print li
#要使用rename得先进入到该文件所在目录,用chdir
chdir("..")
if "hello.txt" in li:
    os.rename("hello.txt", "hi.txt") 
elif "hi.txt" in li:
    os.rename("hi.txt", "hello.txt")

修改后缀

# 修改后缀名
import os  
files = os.listdir(".")
for filename in files:
    pos = filename.find(".")
    if filename[pos + 1:] == "html":
        newname = filename[:pos + 1] + "htm"
        os.rename(filename,newname)

# 修改后缀名2
import os  
files = os.listdir(".")
for filename in files:
    li = os.path.splitext(filename) 
    if li[1] == ".html":
        newname = li[0] + ".htm"
        os.rename(filename,newname)


import re
# 文件的查找
f1 = file("hello.txt", "r")
count = 0
for s in f1.readlines():    
    li = re.findall("hello", s)
    if len(li) > 0:
        count = count + li.count("hello")
print "查找到" + str(count) + "个hello"
f1.close()

# 文件的替换
f1 = file("hello.txt", "r")
f2 = file("hello3.txt", "w")
for s in f1.readlines():    
    f2.write(s.replace("hello", "hi"))
f1.close()
f2.close()


创建/删除文件夹

import os

#当前目录下创建hello文件夹
os.mkdir("hello")
#删除hello文件夹
os.rmdir("hello")
#当前目录下创建hello文件夹,hello文件夹里创建world文件夹
os.makedirs("hello/world")
os.removedirs("hello/world")




类实例

class Student:#类名大写开始
    __name=""#私有成员
    def __init__(self,name):
        self.__name=name
    def getNmae(self):#公有方法,方法名首字母小写,其后的每个单词首字母大写
        return self.__name
if __name__ == '__main__':
    student=Student("borr")
    #print"%s is %d years old "(name,age)
    print student.getNmae()


import random
def compareNum(num1,num2):
    if(num1>num2):
        return 1
    elif(num1==num2):
        return 0
    else:
        return -1
num1=random.randrange(1,9)
num2=random.randrange(1,9)
print"num1=",num1
print"num2=",num2
print compareNum(num1,num2)


如果要在python里使用中文,.py文件开头加一句

# -*- coding: UTF-8 -*-

print "中文"

这样就可以输出中文


str()实现数字类型到字符串类型的转换

a=1
print str(a)


全局变量使用

_a=1
_b=2
def add():
    global _a
    _a=3
    return _a+_b

print add()

结果为5


_a=1
_b=2
def add():
    _a=3
    return _a+_b


print add()

这样结果虽然也是5



while表达式

while(表达式):

      ....

else:

     .....



元组与列表

元组用()表示,一经创立便不可修改

列表用[]表示,可以增删查改

<span style="font-size:18px;">list=[("cd","bb","cc","ddd"),("fv","dv")]

print list
list.extend([("bbb",)])
print "list changed "
for i in range(len(list)):
    for j in range(len(list[i])):
        print list[i][j]
</span>

输出

[('cd', 'bb', 'cc', 'ddd'), ('fv', 'dv')]
list changed 
cd
bb
cc
ddd
fv
dv
bbb


列表查找

<span style="font-size:18px;">list=[("cd","bb","cc","ddd"),("fv","dv")]

list+=[("bbb",)]
print list.index(("bbb",))
#print list.index(("hh",))#throw exception
print ("hh",) in list</span>

输出

2
False


列表插入删除

<span style="font-size:18px;">list=[("cd","bb","cc","ddd"),("fv","dv")]

list.insert(0,("bbb",))
print list
print list.index(("bbb",))
list.pop(1)
print "list changed"
print list</span>

输出

[('bbb',), ('cd', 'bb', 'cc', 'ddd'), ('fv', 'dv')]
0
list changed
[('bbb',), ('fv', 'dv')]


产生一个数值递增列表
num_inc_list = range(30)
#will return a list [0,1,2,...,29]

获取列表长度

len(list)


字典

字典即哈希表

<span style="font-size:18px;">dict={"a":1,2:"b"}
print dict
print dict["a"]
dict["a"]="c"
print dict["a"]
dict["newkey"]="bb"
print dict["newkey"]
del(dict["newkey"])#erase by key,use global function
print "newkey" in dict
print 2 in dict
dict.pop(2)#erase by key,use member function
print 2 in dict
dict[("hh",)]="kk"
print "dict is"
for k in dict:
    print dict[k] </span>

输出


{'a': 1, 2: 'b'}
1
c
bb
False
True
False
dict is
c
kk


关于__init__.py

要想让一个文件夹成为包的必须的文件!这个文件可以为空,但是必须得有!



python可以在函数内部定义函数

<span style="font-size:18px;">def fun (x,y):
    factor=2
    def sum(x,y):
        return (x+y)*factor
    def minus(x,y):
        return x-y
    return sum(x,y)**minus(x,y)

print fun(3,1)</span>

输出

64


格式化字符

<span style="font-size:18px;">str="how are you"
num=1
format= "%s  %d" % (str,num)
print format
</span>

输出

how are you  1


字符串分割

str="how are you,fine"
print str.split(",")

输出

['how are you', 'fine']


字符串拼接

<span style="font-size:18px;">str=("how ","are ","you")
newstr="".join(str)
print newstr

newstr+=" are you"
print newstr</span>

输出

how are you
how are you are you


字符串查找

<span style="font-size:18px;">str="this is an example"
print str.find("is")
print str.rfind("is")</span>

输出

2

5



python中没有类的私有成员修饰符private,声明私有的话可以在私有成员名字前加"__"


<span style="font-size:18px;">class Fruit:
    __color="red"
    def __init__(self):
        self.__change_color()
    def get_color(self):
        return self.__color
    def __change_color(self):
        self.__color="blue"
    def __del__(self):
        print "destruct..."
fr=Fruit()
print fr.get_color()</span>





python多线程


#encoding=utf-8

import threading
import time

class ThreadDemo(threading.Thread):
    def __init__(self, index, create_time): #线程构造函数
        threading.Thread.__init__(self)
        self.index = index
        self.create_time = create_time
    def run(self): #具体的线程运行代码
        time.sleep(1) #休眠1秒钟
        print (time.time()-self.create_time),"\t",self.index
        print "Thread %d exit..." % (self.index)

for index in range(5): 
    thread = ThreadDemo (index, time.time())
    thread.start() #启动线程
print "Main thread exit..."



Numpy基础

from numpy  import *

a = arange(15).reshape(3, 5)

print a

print a.shape[0]
print a.shape[1]

print a.size


输出

[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]

3

5

15


从数组创建

a=array([[2,3,4],
         [5,6,7]])
print a


输出

[[2 3 4]
 [5 6 7]]


tile函数功能是重复某个数组。比如tile(A,n),功能是将数组A重复n次,构成一个新的数组。

from numpy  import *

a=[0,1,2]
b=tile(a,2)
c=tile(a,(2,1))
d=tile(a,(1,2))
print "b:"
print b
print"c:"
print c
print"d:"
print d

输出

b:
[0 1 2 0 1 2]
c:
[[0 1 2]
 [0 1 2]]
d:
[[0 1 2 0 1 2]]


矩阵的创建
由一维或二维数据创建矩阵


from numpy import *;
a1=array([1,2,3]);
a1=mat(a1);
创建常见的矩阵


data1=mat(zeros((3,3)));
#创建一个3*3的零矩阵,矩阵这里zeros函数的参数是一个tuple类型(3,3)
data2=mat(ones((2,4)));
#创建一个2*4的1矩阵,默认是浮点型的数据,如果需要时int类型,可以使用dtype=int
data3=mat(random.rand(2,2));
#这里的random模块使用的是numpy中的random模块,random.rand(2,2)创建的是一个二维数组,需要将其转换成#matrix
data4=mat(random.randint(10,size=(3,3)));
#生成一个3*3的0-10之间的随机整数矩阵,如果需要指定下界则可以多加一个参数
data5=mat(random.randint(2,8,size=(2,5));
#产生一个2-8之间的随机整数矩阵
data6=mat(eye(2,2,dtype=int));
#产生一个2*2的对角矩阵


a1=[1,2,3];
a2=mat(diag(a1));
#生成一个对角线为1、2、3的对角矩阵



1. 矩阵相乘

a1=mat([1,2]);      
a2=mat([[1],[2]]);
a3=a1*a2;
#1*2的矩阵乘以2*1的矩阵,得到1*1的矩阵


2. 矩阵点乘

矩阵对应元素相乘

a1=mat([1,1]);
a2=mat([2,2]);
a3=multiply(a1,a2);

矩阵点乘
a1=mat([2,2]);
a2=a1*2;


3.矩阵求逆,转置 

矩阵求逆
a1=mat(eye(2,2)*0.5);
a2=a1.I;
#求矩阵matrix([[0.5,0],[0,0.5]])的逆矩阵

矩阵转置
a1=mat([[1,1],[0,0]]);
a2=a1.T;

4.计算矩阵对应行列的最大、最小值、和。

a1=mat([[1,1],[2,3],[4,2]]);
计算每一列、行的和

a2=a1.sum(axis=0);//列和,这里得到的是1*2的矩阵
a3=a1.sum(axis=1);//行和,这里得到的是3*1的矩阵
a4=sum(a1[1,:]);//计算第一行所有列的和,这里得到的是一个数值
计算最大、最小值和索引

a1.max();//计算a1矩阵中所有元素的最大值,这里得到的结果是一个数值
a2=max(a1[:,1]);//计算第二列的最大值,这里得到的是一个1*1的矩阵
a1[1,:].max();//计算第二行的最大值,这里得到的是一个一个数值


np.max(a1,0);//计算所有列的最大值,这里使用的是numpy中的max函数
np.max(a1,1);//计算所有行的最大值,这里得到是一个矩阵


np.argmax(a1,0);//计算所有列的最大值对应在该列中的索引
np.argmax(a1[1,:]);//计算第二行中最大值对应在改行的索引

5.矩阵的分隔和合并 
矩阵的分隔,同列表和数组的分隔一致。


a=mat(ones((3,3)));
b=a[1:,1:];//分割出第二行以后的行和第二列以后的列的所有元素
矩阵的合并


a=mat(ones((2,2)));
b=mat(eye(2));
c=vstack((a,b));//按列合并,即增加行数
d=hstack((a,b));//按行合并,即行数不变,扩展列数


4.矩阵、列表、数组的转换
列表可以修改,并且列表中元素可以使不同类型的数据,如下:

l1=[[1],'hello',3];
numpy中数组,同一个数组中所有元素必须为同一个类型,有几个常见的属性:

a=array([[2],[1]]);
dimension=a.ndim;
m,n=a.shape;
number=a.size;//元素总个数
str=a.dtype;//元素的类型
numpy中的矩阵也有与数组常见的几个属性。 
它们之间的转换:


a1=[[1,2],[3,2],[5,2]];//列表
a2=array(a1);//将列表转换成二维数组
a3=array(a1);//将列表转化成矩阵
a4=array(a3);//将矩阵转换成数组
a5=a3.tolist();//将矩阵转换成列表
a6=a2.tolist();//将数组转换成列表
这里可以发现三者之间的转换是非常简单的,这里需要注意的是,当列表是一维的时候,将它转换成数组和矩阵后,再通过tolist()转换成列表是不相同的,需要做一些小小的修改。如下:


a1=[1,2,3];
a2=array(a1);
a3=mat(a1);
a4=a2.tolist();//这里得到的是[1,2,3]
a5=a3.tolist();//这里得到的是[[1,2,3]]
a6=(a4 == a5);//a6=False
a7=(a4 is a5[0]);//a7=True,a5[0]=[1,2,3]
矩阵转换成数值,存在以下一种情况:


dataMat=mat([1]);
val=dataMat[0,0];//这个时候获取的就是矩阵的元素的数值,而不再是矩阵的类型



python进入指定目录

import  os
os.chdir(r 'D:\Pythonwork' #进入指定的目录
  
import  runpy
runpy.run_path( 'hello.py' #运行hello.py文件




你可能感兴趣的:(python)