main入口
if __name__ == '__main__':
print("hello")
python文件操作
python中使用unicode
【BUG】UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-15: ordinal not in range(128)或者UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128)
在python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,python的处理常常会报这样的错,python没办法处理非ascii编码的,此时需要自己设置将python的默认编码,一般设置为utf8的编码格式。
查询系统默认编码可以在解释器中输入以下命令:
Python代码 收藏代码
>>>sys.getdefaultencoding()
设置默认编码时使用:
Python代码 收藏代码
>>>sys.setdefaultencoding('utf8')
可能会报AttributeError: 'module' object has no attribute 'setdefaultencoding'的错误,执行reload(sys),在执行以上命令就可以顺利通过。
此时在执行sys.getdefaultencoding()就会发现编码已经被设置为utf8的了,但是在解释器里修改的编码只能保证当次有效,在重启解释器后,会发现,编码又被重置为默认的ascii了,那么有没有办法一次性修改程序或系统的默认编码呢。
有2种方法设置python的默认编码:
一个解决的方案在程序中加入以下代码:
import sys
reload(sys)
sys.setdefaultencoding('utf8')
另一个方案是在python的Lib\site-packages文件夹下新建一个sitecustomize.py,内容为:
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
此时重启python解释器,执行sys.getdefaultencoding(),发现编码已经被设置为utf8的了,多次重启之后,效果相同,这是因为系统在python启动的时候,自行调用该文件,设置系统的默认编码,而不需要每次都手动的加上解决代码,属于一劳永逸的解决方法。
另外有一种解决方案是在程序中所有涉及到编码的地方,强制编码为utf8,即添加代码encode("utf8"),这种方法并不推荐使用,因为一旦少写一个地方,将会导致大量的错误报告。
enumerate
在python中enumerate的用法多用于在for循环中得到计数,在同时需要index和value值的时候可以使用 enumerate。
enumerate参数为可遍历的变量,如 字符串,列表等; 返回值为enumerate类。
示例代码如下所示:
import string
s = string.ascii_lowercase
e = enumerate(s)
print s
print list(e)
输出为:
abcdefghij
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')]
line 是个 string 包含 0 和 1,要把1都找出来:
方法一:
def read_line(line):
sample = {}
n = len(line)
for i in range(n):
if line[i]!='0':
sample[i] = int(line[i])
return sample
方法二:
def xread_line(line):
return((idx,int(val)) for idx, val in enumerate(line) if val != '0')
print read_line('0001110101')
print list(xread_line('0001110101'))
r和u
在打开文件的时候open(r'c:\....')
加r和不加''r是有区别的
'r'是防止字符转义的 如果路径中出现'\t'的话 不加r的话\t就会被转义 而加了'r'之后'\t'就能保留原有的样子
在字符串赋值的时候 前面加'r'可以防止字符串在时候的时候不被转义 原理是在转义字符前加'\'
例:
s=r'\tt'
print(s)
Output:
'\tt'
s='\tt'
print(s)
Output:
' t'
以r或R开头的python中的字符串表示(非转义的)原始字符串
python里面的字符,如果开头处有个r,比如:
(r’^time/plus/\d{1,2}/$’, hours_ahead)
说明字符串r"XXX"中的XXX是普通字符。
有普通字符相比,其他相对特殊的字符,其中可能包含转义字符,即那些,反斜杠加上对应字母,表示对应的特殊含义的,比如最常见的”\n"表示换行,"\t"表示Tab等。
而如果是以r开头,那么说明后面的字符,都是普通的字符了,即如果是“\n”那么表示一个反斜杠字符,一个字母n,而不是表示换行了。
以r开头的字符,常用于正则表达式,对应着re模块。
在Python的string前面加上‘r’, 是为了告诉编译器这个string是个raw string,不要转意backslash '\' 。 例如,\n 在raw string中,是两个字符,\和n, 而不会转意为换行符。由于正则表达式和 \ 会有冲突,因此,当一个字符串使用了正则表达式后,最好在前面加上'r'。
举例:
原始字符串操作符(r/R),能方便处理反斜杠:
f = open(r'C:\Program
Files\Adobe\Reader 9.0\Setup Files\setup.ini','r')
for i in f:
print i
f.close()
(2)以u或U开头的字符串表示unicode字符串
Unicode是书写国际文本的标准方法。如果你想要用非英语写文本,那么你需要有一个支持Unicode的编辑器。
类似地,Python允许你处理Unicode文本——你只需要在字符串前加上前缀u或U。
举例:
u"This is a Unicode string."
内置数据结构
元组
<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基础
索引与切片
arr=np.arange(10)
arr[5] #索引第6个元素
arr[5:8] #索引第6到第9个元素作为数组
arr[5:8]=12 #令第6到第9个元素等于12
arr_slice=arr[5:8] #数组切片是原始数据的视图,视图上的任何修改都会反映到原数组
arr_slice[:]=64 #将数组切片的全部元素改为64
arr[5:8].copy() #得到数组切片的一份副本
array=[2,3,4,5,6]
1个参数:
array[1:]——从下标为1的元素选择到最后一个元素,返回 [4,5,6]
array[:3]——从下标为0的元素选择到下标为2的元素,不包括下标3的元素,返回[2,3,4]
array[::2]——从下标为0的元素开始,最后一个%2为0的下标对应的那个元素为止
说明:如果前2个参数中有任何一个为负数,那么,分2种情况,如果负数 小于 -n,那么就给负数归0,如果仅仅在-n~0,那么就将这个数理解为0~n-1之间转圈圈就可以了。负数转圈的算法,很简单,就不说了
2个参数:
array[1:-2]——从下标1开始,到下标(n-1)之前的所有元素,返回[3,4]
array[-2:3]——当第一个参数经过计算大于等于后一个,返回空数组[]
array[-13:3]——参见上面第一个说明,第一个参数归0,返回[2,3,4]
3个参数
[::-1]——从头到尾,将数组反转,返回[6,5,4,3,2]
[-1::-2]——从尾到头,每个一个元素,选择一个元素,返回[6,4,2]
说明:没有第3个参数时,切片只能从左向右,此时若第一个参数大于等于第二个参数,则返回空数组
说明:第三个参数<0时,切片方向可以被改变,此时没有上述限制
arr2d=np.array([[1,2,3],[4,5,6],[7,8,9]])
arr2d[2] #索引二维数组第3行
arr2d[0][2] arr2d[0,2] #等价索引1行3列元素
arr2d[:2] #索引第1行和第2行(不含第3行)
arr2d[:,:2] #索引第1列 和第二列
arr2d[:-2] #使用负数索引将从尾部开始选取行,输出[[1,2,3]]
https://www.cnblogs.com/oddcat/articles/9633452.html
arr=np.array([[[[1,3],],], [[[2,4],]], [[[5,2],],]])
a.shape
#(3,1,1,2)
c=a[:,0,0,:]
c
#array([1,3],[2,4],[5,2]])
c.shape
#(3,2)
# 特殊切片截取子串
str1 = "hello world"
print str1[::2]
print str1[1::2]
print str1[::-1]
输出
hlowrd#隔一个
el ol#从index=1开始隔一个
dlrow olloeh
transpose
最近用了矩阵转置 numpy.transpose(),发现了一点有趣的现象:
x=linspace(0,4,5)
#array([0.,1.,2.,3.,4.])
x.shape
#(5, )
想把x从一行,变成一列,如下直接转置会失败:
y=transpose(x) #失败
正确的做法是:
x.shape=(5,1)
y=transpose(x)
查看结果:
y
#array([[0.,1.,2.,3.,4.]])
y.shape
#(1,5)
原来transpose的操作依赖于shape参数,对于一维的shape,转置是不起作用的.
np.newaxis
np.newaxis的功能是插入新维度,看下面的例子:
a=np.array([1,2,3,4,5])
print a.shape
print a
输出结果
(5,)
[1 2 3 4 5]
可以看出a是一个一维数组,
x_data=np.linspace(-1,1,300)[:,np.newaxis]
a=np.array([1,2,3,4,5])
b=a[np.newaxis,:]
print a.shape,b.shape
print a
print b
输出结果:
(5,) (1, 5)
[1 2 3 4 5]
[[1 2 3 4 5]]
x_data=np.linspace(-1,1,300)[:,np.newaxis]
a=np.array([1,2,3,4,5])
b=a[:,np.newaxis]
print a.shape,b.shape
print a
print b
输出结果
(5,) (5, 1)
[1 2 3 4 5]
[[1]
[2]
[3]
[4]
[5]]
可以看出np.newaxis分别是在行或列上增加维度,原来是(6,)的数组,在行上增加维度变成(1,6)的二维数组,在列上增加维度变为(6,1)的二维数组
下一个例子
im = caffe.io.load_image('examples/images/cat.jpg')
print im.shape
#(360, 480, 3)
im_input=im[np.newaxis,:,:,:].transpose(0,3,1,2)
print "data-blobs:",im_input.shape
#data-blobs: (1, 3, 360, 480)
arange
函数说明:函数说明:arange([start,] stop[, step,], dtype=None)根据start与stop指定的范围以及step设定的步长,生成一个 ndarray。
参数含义:start:计数从start开始。默认是从0开始。例如arange(5)等价于range(0, 5);
end:技术到end结束,但不包括end.例如:arange(0, 5) 是[0, 1, 2, 3, 4]没有5
step:每次跳跃的间距,默认为1。例如:arange(0, 5) 等价于 arange(0, 5, 1)
函数返回的是一个ndarray
>>> arange(0,1,0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
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
tile
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]]
np.percentile
百分位数:
第p个百分位数是这样一个值,它使得至少有p%的数据项小于或等于这个值,且至少有(100-p)%的数据项大于或等于这个值
numpy.percentile
Parameters
----------
a : np数组
q : float in range of [0,100] (or sequence of floats)
Percentile to compute。
要计算的q分位数。
axis : 那个轴上运算。
keepdims :bool是否保持维度不变。
Examples
--------
>>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10, 7, 4],
[ 3, 2, 1]])
>>> np.percentile(a, 50) #50%的分位数,就是a里排序之后的中位数
3.5
>>> np.percentile(a, 50, axis=0) #axis为0,在纵列上求
array([[ 6.5, 4.5, 2.5]])
>>> np.percentile(a, 50, axis=1) #axis为1,在横行上求
array([ 7., 2.])
>>> np.percentile(a, 50, axis=1, keepdims=True)
#保持维度不变,这对使用sklearn的fit有好处。
array([[ 7.],
[ 2.]])
array
从数组创建
a=array([[2,3,4],
[5,6,7]])
print a
输出
[[2 3 4]
[5 6 7]]
from numpy import *;
a1=array([1,2,3]);
mat
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的对角矩阵
查询数据类型: .dtype
import numpy as np
c = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]])
print (c.dtype)
# 输出 int32
创建时指定元素类型
import numpy as np
a = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]])
b = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]], dtype='str')
print (a)
print ('---')
print (b)
# 输出 [[ 1 2 3 4]
[ 4 5 6 7]
[ 7 8 9 10]]
---
[['1' '2' '3' '4']
['4' '5' '6' '7']
['7' '8' '9' '10']]
转换数据类型: .astype
import numpy as np
b = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]], dtype='str')
print (b)
# 输出
[['1' '2' '3' '4']
['4' '5' '6' '7']
['7' '8' '9' '10']]
b = b.astype(int)
print (b)
# 输出 [[ 1 2 3 4]
[ 4 5 6 7]
[ 7 8 9 10]]
numpy中的数据类型转换,不能直接改原数据的dtype! 只能用函数astype()
>>> a = np.random.random(4)
>>> a
array([ 0.0945377 , 0.52199916, 0.62490646, 0.21260126])
>>> a.dtype
dtype(‘float64‘)
>>> a.shape
(4,)
改变dtype,发现数组长度翻倍!
>>> a.dtype = ‘float32‘
>>> a
array([ 3.65532693e+20, 1.43907535e+00, -3.31994873e-25,
1.75549972e+00, -2.75686653e+14, 1.78122652e+00,
-1.03207532e-19, 1.58760118e+00], dtype=float32)
>>> a.shape
(8,)
改变dtype,数组长度再次翻倍!
>>> a.dtype = ‘float16‘
>>> a
array([ -9.58442688e-05, 7.19000000e+02, 2.38159180e-01,
1.92968750e+00, nan, -1.66034698e-03,
-2.63427734e-01, 1.96875000e+00, -1.07519531e+00,
-1.19625000e+02, nan, 1.97167969e+00,
-1.60156250e-01, -7.76290894e-03, 4.07226562e-01,
1.94824219e+00], dtype=float16)
>>> a.shape
(16,)
改变dtype=‘float‘,发现默认就是float64,长度也变回最初的4
>>> a.dtype = ‘float‘
>>> a
array([ 0.0945377 , 0.52199916, 0.62490646, 0.21260126])
>>> a.shape
(4,)
>>> a.dtype
dtype(‘float64‘)
把a变为整数,观察其信息
>>> a.dtype = ‘int64‘
>>> a
array([4591476579734816328, 4602876970018897584, 4603803876586077261,
4596827787908854048], dtype=int64)
>>> a.shape
(4,)
改变dtype,发现数组长度翻倍!
>>> a.dtype = ‘int32‘
>>> a
array([ 1637779016, 1069036447, -1764917584, 1071690807, -679822259,
1071906619, -1611419360, 1070282372])
>>> a.shape
(8,)
改变dtype,发现数组长度再次翻倍!
>>> a.dtype = ‘int16‘
>>> a
array([-31160, 24990, 13215, 16312, 32432, -26931, -19401, 16352,
-17331, -10374, -197, 16355, -20192, -24589, 13956, 16331], dtype=int16)
>>> a.shape
(16,)
改变dtype,发现数组长度再次翻倍!
>>> a.dtype = ‘int8‘
>>> a
array([ 72, -122, -98, 97, -97, 51, -72, 63, -80, 126, -51,
-106, 55, -76, -32, 63, 77, -68, 122, -41, 59, -1,
-29, 63, 32, -79, -13, -97, -124, 54, -53, 63], dtype=int8)
>>> a.shape
(32,)
改变dtype,发现整数默认int32!
>>> a.dtype = ‘int‘
>>> a.dtype
dtype(‘int32‘)
>>> a
array([ 1637779016, 1069036447, -1764917584, 1071690807, -679822259,
1071906619, -1611419360, 1070282372])
>>> a.shape
(8,)
很多时候我们用numpy从文本文件读取数据作为numpy的数组,默认的dtype是float64。
但是有些场合我们希望有些数据列作为整数。如果直接改dtype=‘int‘的话,就会出错!原因如上,数组长度翻倍了!!!
下面的场景假设我们得到了导入的数据。我们的本意是希望它们是整数,但实际上是却是浮点数(float64)
>>> b = np.array([1., 2., 3., 4.])
>>> b.dtype
dtype(‘float64‘)
用 astype(int) 得到整数,并且不改变数组长度
>>> c = b.astype(int)
>>> c
array([1, 2, 3, 4])
>>> c.shape
(8,)
>>> c.dtype
dtype(‘int32‘)
如果直接改变b的dtype的话,b的长度翻倍了,这不是我们想要的(当然如果你想的话)
>>> b
array([ 1., 2., 3., 4.])
>>> b.dtype = ‘int‘
>>> b.dtype
dtype(‘int32‘)
>>> b
array([ 0, 1072693248, 0, 1073741824, 0,
1074266112, 0, 1074790400])
>>> b.shape
(8,)
查询矩阵的大小: .shape
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]])
print (a.shape)
print ('---')
print (b.shape)
# 输出 (4,)
---
(3, 4)
通过修改数组的shape属性,在保持数组元素个数不变的情况下,改变数组每个轴的长度。下面的例子将数组b的shape改为(4, 3),从(3, 4)改为(4, 3)并不是对数组进行转置,而只是改变每个轴的大小,数组元素在内存中的位置并没有改变:
b.shape = 4, 3
print (b)
# 输出 [[ 1 2 3]
[ 4 4 5]
[ 6 7 7]
[ 8 9 10]]
当某个轴的元素为-1时,将根据数组元素的个数自动计算该轴的长度,下面程序将数组b的shape改为了(2, 6):
b.shape = 2, -1
print (b)
# 输出 [[ 1 2 3 4 4 5]
[ 6 7 7 8 9 10]]
使用数组的reshape方法,可以创建一个改变了尺寸的新数组,原数组的shape保持不变:
a = np.array((1, 2, 3, 4))
b = a.reshape((2, 2))
b
# 输出 array([[1, 2],
[3, 4]])
only integer arrays with one element can be converted to an index
>>> from numpy import *
>>> a = [3,2,1,4,6,0]
>>> type(a)
<class 'list'>
>>> b = argsort(a)
>>> b
array([5, 2, 1, 0, 3, 4], dtype=int32)
>>> c = b[:-10:-1]
>>> c
array([4, 3, 0, 1, 2, 5], dtype=int32)
>>> a[c]
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
a[c]
TypeError: only integer arrays with one element can be converted to an index
>>> a=array(a) #或a = array([3,2,1,4,6,0])
>>> type(a)
<class 'numpy.ndarray'>
>>> a[c]
array([6, 4, 3, 2, 1, 0])
原来只有numpy里的array能这么用。
np.random
复制
先看一个例子
a = np.array((1, 2, 3, 4))
b = a.reshape((2, 2))
b
# 输出 array([[1, 2],
[3, 4]])
a[2] = 100 # 将数组a的第3个元素改为100,数组d中的2即第三个元素也发生了改变
b
# 输出 array([[1, 2],
[100, 4]])
a和b共享数据存储内存区域,因此修改其中任意一个数组的元素都会同时修改另外一个数组或矩阵的内容
import numpy as np
a = np.arange(12)
b = a
print (a)
print (b)
print (b is a) # 判断b是a?
# 输出 [ 0 1 2 3 4 5 6 7 8 9 10 11]
[ 0 1 2 3 4 5 6 7 8 9 10 11]
True
b.shape = 3, 4
print (a.shape)
# 输出 (3, 4)
print (id(a))
print (id(b))
# 输出 2239367199840
2239367199840
浅复制view
import numpy as np
a = np.arange(12)
b = a.view() # b是新创建出来的数组,但是b和a共享数据
b is a # 判断b是a?
# 输出 False
print (b)
# 输出 [ 0 1 2 3 4 5 6 7 8 9 10 11]
b.shape = 2, 6 # 改变b的shape,a的shape不会受影响
print (a.shape)
print (b)
# 输出 (12,)
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]
b[0, 4] = 1234 # 改变b第1行第5列元素为1234,a对应位置元素受到影响
print (b)
# 输出 [[ 0 1 2 3 1234 5]
[ 6 7 8 9 10 11]]
print (a)
# 输出 [ 0 1 2 3 1234 5 6 7 8 9 10 11]
深复制copy
import numpy as np
a = np.arange(12)
a.shape = 3, 4
a[1, 0] = 1234
c = a.copy()
c is a
c[0, 0] = 9999 # 改变c元素的值,不会影响a的元素
print (c)
print (a)
# 输出 [[9999 1 2 3]
[1234 5 6 7]
[ 8 9 10 11]]
[[ 0 1 2 3]
[1234 5 6 7]
[ 8 9 10 11]]
np.linspace
区间内按元素个数取值
from numpy import pi
np.linspace(0, 2*pi, 100) # 0到2*pi,取100个值
矩阵相乘
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;
Python Numpy.ndarray ValueError:assignment destination is read-only
What is the difference between ndarray and array in numpy?
sum
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,:]);//计算第一行所有列的和,这里得到的是一个数值
np.floor
向下取整
import numpy as np
test = np.floor(10*np.random.random((3, 4)))
print (test)
# 输出 [[ 3. 8. 7. 0.]
[ 5. 9. 8. 2.]
[ 3. 0. 9. 0.]]
矩阵的分隔
a=mat(ones((3,3)));
b=a[1:,1:];//分割出第二行以后的行和第二列以后的列的所有元素
np.hsplit/np.vsplit
import numpy as np
a = np.floor(10*np.random.random((2, 12)))
print (a)
# 输出 [[ 6. 7. 5. 7. 9. 1. 2. 3. 1. 9. 5. 7.]
[ 6. 5. 2. 0. 1. 7. 8. 2. 7. 0. 5. 9.]]
print (np.hsplit(a, 3)) # 按列分割,也就是横方向分割,参数a为要分割的矩阵,参数3为分成三份
print ('---')
print (np.hsplit(a, (3, 4))) # 参数(3, 4)为在维度3前面也就是第4列前切一下,在维度4也就是第5列前面切一下
# 输出 [array([[ 6., 7., 5., 7.],
[ 6., 5., 2., 0.]]), array([[ 9., 1., 2., 3.],
[ 1., 7., 8., 2.]]), array([[ 1., 9., 5., 7.],
[ 7., 0., 5., 9.]])]
---
[array([[ 6., 7., 5.],
[ 6., 5., 2.]]), array([[ 7.],
[ 0.]]), array([[ 9., 1., 2., 3., 1., 9., 5., 7.],
[ 1., 7., 8., 2., 7., 0., 5., 9.]])]
import numpy as np
a = np.floor(10*np.random.random((12, 2)))
print (a)
# 输出 [[ 5. 4.]
[ 8. 7.]
[ 3. 1.]
[ 6. 0.]
[ 4. 4.]
[ 4. 5.]
[ 2. 4.]
[ 7. 3.]
[ 1. 6.]
[ 6. 9.]
[ 2. 1.]
[ 3. 0.]]
print (np.vsplit(a, 3)) # 按行分割,也就是横竖方向分割,参数a为要分割的矩阵,参数3为分成三份
print ('---')
print (np.vsplit(a, (3, 4))) # 参数(3, 4)为在维度3前面也就是第4行前切一下,在维度4也就是第5行前面切一下
# 输出 [array([[ 5., 4.],
[ 8., 7.],
[ 3., 1.],
[ 6., 0.]]), array([[ 4., 4.],
[ 4., 5.],
[ 2., 4.],
[ 7., 3.]]), array([[ 1., 6.],
[ 6., 9.],
[ 2., 1.],
[ 3., 0.]])]
---
[array([[ 5., 4.],
[ 8., 7.],
[ 3., 1.]]), array([[ 6., 0.]]), array([[ 4., 4.],
[ 4., 5.],
[ 2., 4.],
[ 7., 3.],
[ 1., 6.],
[ 6., 9.],
[ 2., 1.],
[ 3., 0.]])]
np.vstack/np.hstack/concatenate/stack/dstack
a=mat(ones((2,2)));
b=mat(eye(2));
c=vstack((a,b));//按列合并,即增加行数
d=hstack((a,b));//按行合并,即行数不变,扩展列数
Python numpy函数hstack() vstack() stack() dstack() vsplit() concatenate()
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
计算最大、最小值和索引
a1=mat([[1,1],[2,3],[4,2]]);
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,:]);//计算第二行中最大值对应在改行的索引
>>> 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])
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
sort
# 方法一:
import numpy as np
a = np.array([[4,3,5,],[1,2,1]])
print (a)
b = np.sort(a, axis=1) # 对a按每行中元素从小到大排序
print (b)
# 输出 [[4 3 5]
[1 2 1]]
[[3 4 5]
[1 1 2]]
# 方法二:
import numpy as np
a = np.array([[4,3,5,],[1,2,1]])
print (a)
a.sort(axis=1)
print (a)
# 输出 [[4 3 5]
[1 2 1]]
[[3 4 5]
[1 1 2]]
# 方法三:
import numpy as np
a = np.array([4, 3, 1, 2])
b = np.argsort(a) # 求a从小到大排序的坐标
print (b)
print (a[b]) # 按求出来的坐标顺序排序
# 输出 [2 3 1 0]
[1 2 3 4]
numpy.unique
unique()保留数组中不同的值,返回两个参数。
>>> a=np.random.randint(0,5,8)
>>> a
array([2, 3, 3, 0, 1, 4, 2, 4])
>>> np.unique(a)
array([0, 1, 2, 3, 4])
>>> c,s=np.unique(b,return_index=True)
>>> c
array([0, 1, 2, 3, 4])
>>> s
array([3, 4, 0, 1, 5])(元素出现的起始位置)
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()会影响原始矩阵。
>>> x = np.array([[1, 2], [3, 4]])
>>> x.flatten()[1] = 100
>>> x
array([[1, 2],
[3, 4]]) # flatten:返回的是拷贝
>>> x.ravel()[1] = 100
>>> x
array([[ 1, 100],
[ 3, 4]])
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
将条件逻辑表述为数组运算
Numpy.where函数是三元表达式x if condition else y的矢量化版本
xarr=np.array([1.1,1.2,1.3,1.4,1.5]) #两个数值数组
yarr=np.array([2.1,2.2,2.3,2.4,2.5])
cond=np.array([True,False,True,True,False]) #一个布尔数组
result=np.where(cond,xarr,yarr) #三元表达式
#result=array([1.1,2.2,1.3,1.4,2.5])
random.randn
random.randint
random.randint(2,8,size=(2,5)
用于数组的文件输入输出
Numpy能够读写磁盘上的文本数据或二进制数据。
arr=np.arange(10)
np.save(‘some_array’,arr) #数组以未压缩的原始二进制格式保存在.npy文件中
np.load(‘some_array’) #通过np.load读取磁盘上的数组
np.savez(‘array_archive.npz’,a=arr,b=arr) #将多个数组以保存在一个压缩文件中
a=np.arange(0,12,0.5).reshape(4,-1)
np.savetxt(‘E:\\knakan\\a.txt’,a) #缺省按照’%.18e’格式保存数据,以空格分隔
np.loadtxt(‘E:\\kankan\\a.txt’)
np.savetxt(‘E:\\kankan\\a.txt’,a,fmt=”%d”,delimiter=”,”) #改为保存为整数,以逗号分隔
np.loadtxt(‘E:\\kankan\\a.txt’,delimiter=”,”) #读入时也需指定逗号分隔
http://blog.youkuaiyun.com/pipisorry/article/category/2558181
scipy
scipy.sparse.csr_matrix
http://blog.youkuaiyun.com/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, Circle
import 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, 0
ax.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()
ax.add_patch(
plt.Rectangle((20, 100),#左上角坐标
200,#宽度
40, #高度
fill=False,
edgecolor='red', linewidth=3.5)
)
matplotlib绘图实例:pyplot、pylab模块及作图参数
http://blog.youkuaiyun.com/pipisorry/article/category/2627547
调试
1万+

被折叠的 条评论
为什么被折叠?



