python学习笔记
来源:互联网 发布:淘宝号信誉度查询 编辑:程序博客网 时间:2024/05/19 17:58
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 assignmentt = ("apple",)t = ()print tuple[-1]print tuple[-2]#print t[0]</span>
输出
<span style="font-size:18px;">orangegrape</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 tuple2print tuple3print tuple4fruit1 = ("apple", "banana")fruit2 = ("grape", "orange")tuple = (fruit1, fruit2)print tupleprint "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 = tupleprint a, b, c, d</span>输出
<span style="font-size:18px;">orangegrape('banana', 'grape')('apple', 'banana')()(('apple', 'banana'), ('grape', 'orange'))tuple[0][1] = bananatuple[1][1] = orangeapple 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 = 0for 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 listprint list[2]list.append("watermelon")list.insert(1, "grapefruit")print listlist.remove("grape")print list#list.remove("a")print list.pop()print listlist = ["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 listprint list2list3=[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 listlist = ["apple", "banana", "grape", "orange"]print list.index("grape")print list.index("orange")print "orange" in listlist1 = ["apple", "banana"]list2 = ["grape", "orange"]list1.extend(list2)print list1list3 = ["watermelon"]list1 = list1 + list3print list1list1 += ["grapefruit"]print list1list1 = ["apple", "banana"] * 2print list1#使用列表的sort方法排序list = ["banana", "apple", "orange", "grape"]list.sort()print "Sorted list:", listlist.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']23True['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 dictprint dict["a"]#使用数字作为索引dict = {1 : "apple", 2 : "banana", 3 : "grape", 4 : "orange"}print dictprint dict[2]#字典的添加、删除dict = {1 : "apple", 2 : "banana", 3 : "grape", 4 : "orange"}del dict[1]print dictprint dict[2]#使用元组作为索引dict = {}dict[("a","p","p","l","e")] = "apple"dict[("b","a","n","a","n","a")] = "banana"print dictprint 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 dictdict.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, vfor (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] = appledict[b] = bananadict[o] = orangedict[g] = grape[('a', 'apple'), ('c', 'grape'), ('b', 'banana'), ('d', 'orange')]dict[a] = appledict[b] = bananadict[o] = orangedict[g] = grape<dictionary-itemiterator object at 0x02659690>dict[a] = appledict[c] = grapedict[b] = bananadict[d] = orangedict[a] = appledict[c] = grapedict[b] = bananadict[d] = orange('apple',)apple{'b': 'banana', 'o': 'orange'}orange['grape', 'grapefruit']grapefruit</span>
<span style="font-size:18px;">#字典的更新dict = {"a" : "apple", "b" : "banana"}print dictdict2 = {"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 copydict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}} dict2 = copy.deepcopy(dict)dict3 = copy.copy(dict)dict2["b"]["g"] = "orange"print dictdict3["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.0format = "%s" % str1print formatformat = "%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;">versionversion 1浮点型数字: 1.250000浮点型数字: 1.2浮点型数字: 1.25version: 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 pathprint len(path) path = r"hello\tworld\n" print pathprint len(path) # strip()去掉转义字符word = "\thello world\n"print "直接输出:", wordprint "strip()后输出:", word.strip()print "lstrip()后输出:", word.lstrip()print "rstrip()后输出:", word.rstrip()</span>
<span style="font-size:18px;">helloworld12hello\tworld\n14直接输出: hello worldstrip()后输出: hello worldlstrip()后输出: hello worldrstrip()后输出: hello world</span>
字符串连接
<span style="font-size:18px;"># -*- coding: UTF-8 -*-# 使用"+"连接字符串str1 = "hello "str2 = "world "str3 = "hello "str4 = "China "result = str1 + str2 + str3result += str4print result# 使用join()连接字符串strs = ["hello ", "world ", "hello ", "China "]result = "".join(strs)print result# 使用reduce()连接字符串import operatorstrs = ["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']419927234943512worhlowrdel ol</span>
字符串反转
<span style="font-size:18px;"># -*- coding: UTF-8 -*-# 使用list的reverse()def reverse(s): li = list(s) li.reverse() s = "".join(li) return sprint reverse("hello")# 循环输出反转的字符串def reverse(s): out = "" li = list(s) for i in range(len(li), 0, -1): out += "".join(li[i-1]) return outprint reverse("hello")# 特殊切片反转字符串def reverse(s): return s[::-1]print reverse("hello")</span>
输出
<span style="font-size:18px;">olleholleholleh</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;">810</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 Chinahi world, hello Chinahello world, hello China</span>
文件操作
创建文件
# 创建文件context = '''hello worldhello 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: breakf.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 contextf.close()# read(size)f = open("hello.txt")context = f.read(5) print contextprint f.tell()context = f.read(5) print contextprint f.tell()f.close()
hello.txt内容如下
hello worldhello China
输出
hello worldhello China hello worldhello China hello worldhello China hello5 worl10
写入文件
# 使用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 osfile("hello.txt", "w")if os.path.exists("hello.txt"): os.remove("hello.txt")
目录基础知识
/表示根目录, ./表示当前路径, ../表示上一级父目录
./SRC/ 这样写表示,当前目录中的SRC文件夹; ../SRC/ 这样写表示,当前目录的上一层目录中SRC文件夹; /SRC/ 这样写表示,项目根目录(可以只磁盘根目录,也可以指项目根目录,具体根据实际情况而定)
# 使用read()、write()实现拷贝# 创建文件hello.txtsrc = file("hello.txt", "w")li = ["hello world\n", "hello China\n"]src.writelines(li) src.close()# 把hello.txt拷贝到hello2.txtsrc = file("hello.txt", "r")dst = file("hello2.txt", "w")dst.write(src.read())src.close()dst.close()# shutil模块实现文件的拷贝import shutilshutil.copyfile("hello.txt","hello2.txt")#将hello.txt移动到上一级目录shutil.move("hello.txt","../")#当前目录下hello2.txt不存在了,只有hello3.txtshutil.move("hello2.txt","hello3.txt")
文件重命名
# 修改文件名import osfrom nt import chdir#列出当前目录的父目录下的文件#同理os.listdir(".")列出当前目录下的文件li = os.listdir("..")print li#要使用rename得先进入到该文件所在目录,用chdirchdir("..")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)# 修改后缀名2import 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 = 0for 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 listlist.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 exceptionprint ("hh",) in list</span>
输出
2
False
列表插入删除
<span style="font-size:18px;">list=[("cd","bb","cc","ddd"),("fv","dv")]list.insert(0,("bbb",))print listprint 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 dictprint dict["a"]dict["a"]="c"print dict["a"]dict["newkey"]="bb"print dict["newkey"]del(dict["newkey"])#erase by key,use global functionprint "newkey" in dictprint 2 in dictdict.pop(2)#erase by key,use member functionprint 2 in dictdict[("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=1format= "%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 newstrnewstr+=" 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-8import threadingimport timeclass 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];//这个时候获取的就是矩阵的元素的数值,而不再是矩阵的类型
argmax,max
>>> import numpy as np
>>> a = np.arange(15).reshape(3, 5)
>>> print a
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
>>> print a.shape
(3, 5)
>>> np.argmax(a) //取得最大的一个元素的下标
14
>>> np.argmax(a,axis=0)//取得每一列中最大的元素的下标,如[0,5,10],最大为10,下标为2
array([2, 2, 2, 2, 2])
>>> a.argmax(axis=1)//取得每一行中最大的元素的下标,如[5,6,7,8,9],最大为9,下标为4
array([4, 4, 4])
>>> a[2][4]=15
>>> print a
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 15]]
>>> a.argmax()
14
>>> a.max(axis=1)//取得每一行的最大值
array([ 4, 9, 15])
>>>
where
>>a = [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>idx = [idx for (idx, val) in enumerate(a) if val > 2]
>>idx
[2, 5, 8]
>>vals = [val for (idx, vals) in enumerate(a) if val > 2]
[3, 3, 3]
>>a = np.array(a)
>>a
array([1, 2, 3, 1, 2, 3, 1, 2, 3])
>>idx = np.where(a > 2)
>>idx
(array([2, 5, 8], dtype=int32),)
>>a[idx] # 这种做法并不推荐
array([3, 3, 3])
>>a[a>2] # 推荐的做法
array([3, 3, 3])
Numpy基础笔记
meshgrid
meshgrid 的使用方法:
[X,Y] = meshgrid(x,y) 将向量x和y定义的区域转换成矩阵X和Y,这两个矩阵可以用来表示mesh和surf的三维空间点以及两个变量的赋值。其中矩阵X的行向量是向量x的简单复制,而矩阵Y的列向量是向量y的简单复制。
meshgrid用于从数组a和b产生网格。生成的网格矩阵A和B大小是相同的。它也可以是更高维的。
[A,B]=Meshgrid(a,b)
生成size(b)Xsize(a)大小的矩阵A和B。它相当于a从一行重复增加到size(b)行,把b转置成一列再重复增加到size(a)列。因此命令等效于:
A=ones(size(b))*a;
B=b'*ones(size(a))
如下所示:
>> a=[1:2]
a =
1 2
>> b=[3:5]
b =
3 4 5
>> [A,B]=meshgrid(a,b)
A =
1 2
1 2
1 2
B =
3 3
4 4
5 5
>> [B,A]=meshgrid(b,a)
B =
3 4 5
3 4 5
A =
1 1 1
2 2 2
numpy.random中的shuffle和permutation
numpy.random.shuffle(x) and numpy.random.permutation(x),这两个有什么不同,或者说有什么关系?
np.random.permutation与np.random.shuffle有两处不同:
如果传给permutation一个矩阵,它会返回一个洗牌后的矩阵副本;
而shuffle只是对一个矩阵进行洗牌,无返回值。 如果传入一个整数,它会返回一个洗牌后的arange。
下面的源码可以看出来:
3280 def permutation(self, object x):
...
3307 if isinstance(x, (int, np.integer)):
3308 arr = np.arange(x)
3309 else:
3310 arr = np.array(x)
3311 self.shuffle(arr)
3312 return arr
flatten和ravel
首先声明两者所要实现的功能是一致的(将多维数组降位一维),两者的区别在于numpy.flatten()返回一份拷贝,对拷贝所做的修改不会影响原始矩阵,而numpy.ravel()会影响原始矩阵。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
http://blog.csdn.net/pipisorry/article/category/2558181
scipy
scipy.sparse.csr_matrix
SciPy教程 - 稀疏矩阵库scipy.sparse
http://blog.csdn.net/pipisorry/article/category/2760105
python进入指定目录
import
os
os.chdir(r
'D:\Pythonwork'
)
#进入指定的目录
import
runpy
runpy.run_path(
'hello.py'
)
#运行hello.py文件
python中表示或与关系
python中没有&&,用and表示,没有|,用or表示
matplotlib绘图
#################################### !/usr/bin/env python# coding=utf-8# __author__ = 'pipi'# ctime 2014.10.11# 绘制椭圆和圆形###################################from matplotlib.patches import Ellipse, Circleimport matplotlib.pyplot as plt fig = plt.figure()ax = fig.add_subplot(111) ell1 = Ellipse(xy = (0.0, 0.0), width = 4, height = 8, angle = 30.0, facecolor= 'yellow', alpha=0.3)cir1 = Circle(xy = (0.0, 0.0), radius=2, alpha=0.5)ax.add_patch(ell1)ax.add_patch(cir1) x, y = 0, 0ax.plot(x, y, 'ro') plt.axis('scaled')# ax.set_xlim(-4, 4)# ax.set_ylim(-4, 4)plt.axis('equal') #changes limits of x or y axis so that equal increments of x and y have the same length plt.show()
matplotlib绘图实例:pyplot、pylab模块及作图参数
matplotlib绘图基础
http://blog.csdn.net/pipisorry/article/category/2627547
python的matplotlib显示图片
matplotlib绘图库入门
调试
Python 代码调试技巧
使用PyCharm来远程调试Python
- 【python】:python学习笔记
- Python学习笔记-Python起步
- Python学习笔记-Python基础
- Python学习笔记-Python对象
- Python基本概念--Python学习笔记
- Python学习笔记:Python函数
- python学习笔记-python安装
- Python学习笔记--Python基础
- 【Python】python基础学习笔记
- python学习笔记3
- Python学习笔记
- Boost.Python学习笔记
- python学习笔记1
- python学习笔记2
- python学习笔记(2)
- Python学习笔记 Module
- Python学习笔记.
- python学习笔记(1)
- eclipse-整合struts和spring-maven
- 表格 标签属性
- Http Requests for PHP
- spring单元测试使用
- 深入理解Java1:SimpleDateFormat安全的时间格式化
- python学习笔记
- 学习笔记—二叉树中求度为2的节点个数
- Mysql日期函数使用汇总
- Java反射知识点总结
- 【SSH项目实战】国税协同平台-17.权限鉴定&解决登录嵌套
- MySql中having字句对组记录进行筛选使用说明
- java---用两个栈实现队列&&用两个队列实现栈
- 国嵌嵌入式学习笔记之学习方法
- Java代码复用