最近无论是自己写程序还是看别人的开源程序,经常发现自己遗忘一些基本的Python知识,还得到网上查。遂抽出两天时间,复习(yu xi)python,把自己老容易忘掉的知识点总结成这个小抄的形式~


画图 Plot与Matplotlib 基础

Python提供了一个很像MATLAB的绘图接口。



from numpy import array
from matplotlib.pyplot import plot
a = array([1, 2, 3, 4, 5, 6, 7, 8])
plot(a, a**2)





python array无逗号 python中的array_Python


plot(y)

plot(x, y) plot(x, y, format_string)
只给定 y 值,默认以下标为 x 轴:


%matplotlib inline
x = linspace(0, 2 * pi, 50)
plot(sin(x))
plot(x, sin(x))


python array无逗号 python中的array_sed_02


plot(x, sin(x),
    x, sin(2 * x))


python array无逗号 python中的array_python 循环添加array_03


plot(x, sin(x), 'b-o',
    x, sin(2 * x), 'r-^')


python array无逗号 python中的array_python 循环添加array_04


散点图


scatter(x, sin(x))


python array无逗号 python中的array_python array无逗号_05


直方图

从高斯分布随机生成1000个点得到的直方图:


hist(randn(1000))


python array无逗号 python中的array_sed_06


文件操作 File IO

写文件


f = open('路径', 'w')
f.write('1 2 3 4n')
f.write('2 3 4 5n')
f.close()


读文件


f = open('路径')
data = []
for line in f:
    data.append([field for field in line.split()])
f.close()
data


输出结果


[['1', '2', '3', '4'], ['2', '3', '4', '5']]


注:Python中有一种叫做列表推导式(List comprehension)的用法


numbers = [int(field) for field in fields]
numbers


输出结果:[1, 2, 3, 4, 5]

删除文件:


import os
os.remove('路径')


类 Class

class来定义一个类。 Person(object)表示继承自object类; __init__函数用来初始化对象; self表示对象自身,类似于CJava里面this


class Person(object):
    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age
    def full_name(self):
        return self.first + ' ' + self.last


这就涉及到为什么要用类与对象,我们可以使用人的那个类,造出好多不同的人(对象)。


Mertle = Person('Mertle', 'Sedgewick', 52)
Tom = Person('Tom', 'Swift', 28)
Tom.age


结果输出28,同理你可以得到任何已知对象的任何信息。

改变列表的方法

l.append(ob) 将元素 ob 添加到列表 l 的最后。


a = [10, 11, 12]
a.append(11)
print a


输出:[10, 11, 12, 11]


a.append([11, 12])
print a


输出:[10, 11, 12, 11, [11, 12]]

向列表添加序列:l.extend(lst) 将序列 lst 的元素依次添加到列表 l 的最后,作用相当于 l += lst


a = [10, 11, 12, 11]
a.extend([1, 2])
print a


输出:[10, 11, 12, 11, 1, 2]

插入元素:l.insert(idx, ob) 在索引 idx 处插入 ob ,之后的元素依次后移。


a = [10, 11, 12, 13, 11]
# 在索引 3 插入 'a'
a.insert(1, 'a')
print (a)


输出:[10, 'a', 11, 12, 13, 11]

移除元素:l.remove(ob) 会将列表中第一个出现的 ob 删除,如果 ob 不在 l 中会报错。


a = [10, 11, 12, 13, 11]
# 移除了第一个 11
a.remove(11)
print a


输出:[10, 12, 13, 11]

弹出元素:l.pop(idx) 会将索引 idx 处的元素删除,并返回这个元素。


a = [10, 11, 12, 13, 11]
a.pop(2)


输出:12

排序l.sort() 会将列表中的元素按照一定的规则排序。
列表反向l.reverse() 会将列表中的元素从后向前排列。

continue 语句与break 语句

遇到 continue 的时候,程序会返回到循环的最开始重新执行。
例如在循环中忽略一些特定的值:


values = [7, 6, 4, 7, 19, 2, 1]
for i in values:
    if i % 2 != 0:
        # 忽略奇数
        continue
    print (i/2)


输出为:

3.0
2.0
1.0

遇到 break 的时候,程序会跳出循环,不管循环条件是不是满足。

函数接收不定参数

使用如下方法,可以使函数接受不定数目的参数:


def add(x, *args):
    total = x
    for arg in args:
        total += arg
    return total
add(1,2,3,4)


输出为:10

通过 map 的方式利用函数来生成序列


def sqr(x): 
    return x ** 2

a = [2,3,4]
print map(sqr, a)


输出为:[4, 9, 16]

其用法为:


map(aFun, aSeq)


将函数 aFun 应用到序列 aSeq 上的每一个元素上,返回一个列表,不管这个序列原来是什么类型。

事实上,根据函数参数的多少,map 可以接受多组序列,将其对应的元素作为参数传入函数。

__name__ 属性

有时候我们想将一个 .py 文件既当作脚本,又能当作模块用,这个时候可以使用 __name__ 这个属性。

只有当文件被当作脚本执行的时候, __name__的值才会是 '__main__',所以我们可以


%%writefile ex2.py

PI = 3.1416

def sum(lst):
    """ Sum the values in a list
    """
    tot = 0
    for value in lst:
        tot = tot + value
    return tot

def add(x, y):
    " Add two values."
    a = x + y
    return a

def test():
    w = [0,1,2,3]
    assert(sum(w) == 6)
    print ('test passed.')
    
if __name__ == '__main__':
    test()


运行文件:


%run ex2.py


输出:test passed.

当作模块导入, test() 不会执行:


import ex2


但是可以使用其中的变量:


ex2.PI


输出:3.1416

也可以从模块中导入变量:


from ex2 import add, PI


使用 from 后,可以直接使用 addPI

try & except 块

写代码的时候,出现错误必不可免,即使代码没有问题,也可能遇到别的问题。一旦报错,程序就会停止执行,如果不希望程序停止执行,那么我们可以添加一对 try & except


import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = 1 / math.log10(x)
        print "log10({0}) = {1}".format(x, y)
   except ValueError:
        print "the value must be greater than 0"
    except ZeroDivisionError:
        print "the value must not be 1"
    except Exception:
        print "unexpected error"


except后面跟着错误类型,如果有该错误,则执行其后语句。

try/catch 块还有一个可选的关键词 finally。

不管 try 块有没有异常, finally 块的内容总是会被执行,而且会在抛出异常前执行,因此可以用来作为安全保证,比如确保打开的文件被关闭。


try:
    print 1
finally:
    print 'finally was called.'


输出:


1
finally was called.


numpy画图

linspace 用来生成一组等间隔的数据:


a = linspace(0, 2*pi, 21)
%precision 3
a


输出


array([0.   , 0.314, 0.628, 0.942, 1.257, 1.571, 1.885, 2.199, 2.513,
       2.827, 3.142, 3.456, 3.77 , 4.084, 4.398, 4.712, 5.027, 5.341,
       5.655, 5.969, 6.283])


三角函数,作图


b = sin(a)
%matplotlib inline
plot(a, b)


python array无逗号 python中的array_sed_07


数组求和


a = array([[1,2,3], 
           [4,5,6]])
sum(a)


输出21

指定求和的维度:
沿着第一维求和:


sum(a, axis=0)


输出:array([5, 7, 9])

沿着第二维求和


sum(a, axis=1)


输出:array([ 6, 15])

沿着最后一维求和


sum(a, axis=-1)


输出:array([ 6, 15])

求最大最小值的位置


a.argmin()


输出0

近似到一位小数:

round方法


a = array([1.35, 2.5, 1.5])
a.round()


输出:array([ 1., 2., 2.])


a.round(decimals=1)


输出:array([ 1.4, 2.5, 1.5])