python

Python

2016-04-05  本文已影响552人  Rco

Since Jan.26th,2016

1、ubuntu 下运行 python 的几种方式

2、关于print时代码的多行输入

但是用\则正常。

  print('\'\'\'')

另外,正则表达式中的一些特殊符号似乎也不能用r转义,比如输出.就必须用代码\.来实现。

3、递归函数中的ifreturn

输出得到的是120,即5!,事实上当进行到5×4×3×2×fact(1)的时候,由于n == 1,因此return得到的不再是一个表达式,而是常数1,从而,返回的5×4×3×2×fact(1)也成为了一个确定的值,120,函数return一个确定值的目标已经的达到,也就不再进行接下来的语句,即函数调用完毕了。
但是
x=19
if x >= 17:
print(x)
print(x)
则会得到两个19的输出结果,因为if语句的语法中就没有执行后跳过下面所有语句的定义,仍会执行print(x)

4、range()的用法

我们所做的只是提供两个数,range返回一个序列的数。这个序列从第一个数开始到第二个数为止。例如,range(1,5)给出序列[1, 2, 3, 4]。默认地,range的步长为1。如果我们为range提供第三个数,那么它将成为步长。例如,range(1,5,2)给出[1,3]。记住,range 向上延伸到第二个数,即它不包含第二个数。
在C/C++中,如果你想要写for (int i = 0; i < 5; i++),那么用Python,你写成for i in range(0,5)。你会注意到,Python的for循环更加简单、明白、不易出错。
http://old.sebug.net/paper/python/ch06s04.html

range输出的是有序的。

for i in xrange(5):
    print i, 
    i = 100
    print i

输出为:

0 100
1 100
2 100
3 100
4 100

显然,每次执行完i = 100的语句并输出后,进行下一次循环时,i又变成了下一个数,而与100无关了。
所以,forrange的这一条组合式的语句有两个意义:
1.提供了一个一定次数的循环。
2.为每次循环提供了一定一个按照固定规律变化的值(i)。

5、输出时* times的用法

6、enumerate的用法

# iter list with index:
  print('iter enumerate([\'A\', \'B\', \'C\']')
  for i, value in enumerate(['A', 'B', 'C']):
      print(i, value)

https://github.com/michaelliao/learn-python3/blob/master/samples/advance/do_iter.py

得到的输出结果为

iter enumerate(['A', 'B', 'C'])
  0 A
  1 B
  2 C

因此,就可以通过这种方式把list变成索引-元素对,在迭代时同时迭代这二者。

7、isinstance的用法

8、关于内置字符串处理函数

这是第二段:
def normalize(name):
return name.upper()[0] + name.lower()[1:]

  L1 = ['adam', 'LISA', 'barT']
  L2 = list(map(normalize, L1))
  print(L2)

输出结果都是
['Adam', 'Lisa', 'Bart']

9、关于在dictionary中通过value查找key

输出结果为

  amber

特别注意:上述的x和y都是任意更换的,完全可以换成name和age,即字典被创建的时候key和value是没有变量来指向的,无论是x,y还是name,age都是临时用来迭代的。

10、关于切片

11、关于字符串或list相等的比较

12、关于字符串和list的方法

13、关于python输出时取消自动换行

14、含有0个或1个项目的元组

一个空的元组由一对空的圆括号组成,如myempty = ()。然而,含有单个元素的元组就不那么简单了。你必须在第一个(唯一一个)项目后跟一个逗号,这样Python才能区分元组和表达式中一个带圆括号的对象。即如果你想要的是一个包含项目2
的元组的时候,你应该指明singleton = (2 , )
http://old.sebug.net/paper/python/ch09s03.html

也就是说
string = (2)
print(5 - string)
这时string被认为是一个int,输出为
3

string = (2,)
print(5 - string)
此时string才被认为是一个tuple,会报错。

15、关于字典增加元素

16、关于file和open方法

17、关于pickle模块

18、关于range和xrange

19、关于decode和encode

19、关于正则表达式

20、关于文件读写

r 只能读
r+ 可读可写,不会创建不存在的文件。如果直接写文件,则从顶部开始写,覆盖之前此位置的内容,如果先读后写,则会在文件最后追加内容。
w+ 可读可写 如果文件存在 则覆盖整个文件 不存在则创建
w 只能写 覆盖整个文件 不存在则创建
a 只能写 从文件底部添加内容 不存在则创建
a+ 可读可写 从文件顶部读取内容 从文件底部添加内容 不存在则创建
https://segmentfault.com/q/1010000003813594

21 、关于urllib(urllib2)模块

输出为
212251
0

22、关于PyQt

23、关于中文字符编码

24、关于错误处理时的 try 语句

25、关于 Windows 和 Linux 跨平台的问题

26、判断变量或字符是否为整数的方法

27、关于 and 和 or 以及 not 的优先顺序

28、关于删除数组中元素的几种方法(del,remove,pop)

29、关于排列组合

30、关于 set 和 list 的性能问题

31、爬虫中将cookie的字符串转化为字典形式

以上代码将&作为连接字符,具体因情况而变。

32、scipy内模块的导入问题

33、科学计算时的浮点数和整数

33、解方程

34、求导数

import sympy
expression = sympy.diff('3.0*x**2.0+2.0*x')
print expression
print type(expression)

输出:

6*x + 2
<class 'sympy.core.add.Add'>

还可以配合sympy.solve一起使用(求导数的零点):

x0 = sympy.solve(sympy.diff(expression))
print x0
[-0.333333333333333]

35、numpy 中的 mgridmeshgrid

>>> x1 = np.arange(1, 11, 2)
>>> y1 = np.arange(-12, -3, 3)
>>> x1, y1 = np.meshgrid(x1,y1)
>>> x1
array([[1, 3, 5, 7, 9], 
         [1, 3, 5, 7, 9],
         [1, 3, 5, 7, 9]])
>>> y1
array([[-12, -12, -12, -12, -12],
         [ -9, -9, -9, -9, -9],
         [ -6, -6, -6, -6, -6]])
>>> x2, y2 = np.mgrid[1:11:2, -12:-3:3]
>>> x2
array([[1, 1, 1],
        [3, 3, 3],
        [5, 5, 5],
        [7, 7, 7],
        [9, 9, 9]])
>>> y2
array([[-12, -9, -6],
        [-12, -9, -6],
        [-12, -9, -6],
        [-12, -9, -6],
        [-12, -9, -6]])

另一种用法是不提供步长参数,但提供数量参数

xs,ys = np.mgrid[-4:1:30j,0.8:1.1:30j] 

其中的30j表示的是从 start 到 end 的总个数,如果两个不一致,会取大的那个。保证两者个数一致。

36、matplotlib 画图

import matplotlib.pyplot as plt
plt.figure()
ax = plg.gca()
ax.set_aspect(1) # 使横纵坐标轴对单位区间的实际长度(axes per unit length)相等
plt.plot(x,y,'rx-',linewidth=2,markersize=5,label='test')
plt.xlim([-1,1])
plt.title()
plt.xlabel()
plt.ylabel()
plt.legend()
plt.show()
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.plot(xs,ys,'rx-',zs=zs,linewidth=2,markersize=5,label='test')
ax.set_zlim([-1,1])
plt.title()
ax.set_title()
ax.set_xlabel()
ax.set_ylabel()
ax.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

  k,b=np.mgrid[1:3:3j,4:6:3j]
  f_kb=3*k+2*b+1

  fig = plt.figure()
  ax = fig.add_subplot(111,projection='3d')
  ax.plot_surface(k,b,f_kb)
  plt.show()

在画 3D 图前,我们一般用mgridmeshgrid来生成需要 x,y轴上的变量矩阵。画 3D 图的要求是 z 矩阵的行数等于 x 矩阵的行数列数等于 y 矩阵的列数。也就是由如下的对应关系(以 3 阶矩阵为例):

y1,1 y1,2 y1,3
x1,1 z1,1 z1,2 z1,3
x2,1 z2,1 z2,2 z2,3
x3,1 z3,1 z3,2 z3,3

mgrid为例,我们看mgrid生成的矩阵可以发现,x 的每一行都是一样的,而 y 的每一列都是一样的,这其实是为了代入 z 的函数进行计算比较方便,比如 z 就可以直接生成z = 2*x + 3*y,正好是一一对应的。
colorbar:注意,如果要显示 colorbar,需要在 plot_surface 时先指定映射

from matplotlib import cm
 ax.plot_surface(k,b,f_kb,cmap=cm.coolwarm)
fig.colorbar(surf, shrink=0.5, aspect=5)
ax.legend()
k,b=np.mgrid[1:3:3j,4:6:3j]
f_kb=3*k+2*b+1

  fig = plt.figure()
  ax = fig.add_subplot(111)
  ax.contour(k,b,f_kb,np.logspace(-2, 2, 70))
  plt.show()

在处理数据时和 3D 曲面图是一样的,都是用到了mgridmeshgrid函数,而上述代码中contour的第四个参数是指 z 轴取 0.01 到 100 之间,并划分成70个平面,即有 70 条等高线充满这个范围(但实际显示可能不到70条,因为还要看 x 轴和 y 轴的范围限制)。

如果我只想画出 z=1,z=2,z=3 这 3 条等高线呢?
plt.contour(X, Y, Z,[1,2,3])

要注意的是contour(X, Y, Z,1)的意思是只画一条等高线出来,至于是哪一条,就不知道了,而contour(X, Y, Z,[1])的意思是画出 z=1 的这一条等高线。
http://blog.csdn.net/william_2015/article/details/47304687

如果需要对等高线加上图例,不能直接通过ax.contour(xc,yc,zc,label='text')实现,而需要单独设置,比如:

CS = ax.contour(xc,yc,zc)
CS.collections[0].set_label('text')
ax.legend()

同样地,设置 linewidth 等属性也类似,使用CS.collections[0].set_linewidth(2)等语句来实现。
其实,等高线图可以直接在图上标出每条线代表的值,而不需要通过图例。具体代码如下:

CS = ax.contour(xc,yc,zc)
ax.clabel(CS)

因为这不是图例,所以不需要legend方法即可显示。
最后,如果要画 3D 的等高线图,只要将

ax = fig.add_subplot(111)

改为

ax = fig.add_subplot(111,projection='3d')

即可。

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212,projection='3d')
plt.show()
color_bg = (0.1843,0.3098,0.3098)
color_green = 'g'
color_yellow = '#f06215'
color_white = '#ffffff'
color_red = 'r'
fig = plt.figure(facecolor=color_bg) # 设置外围颜色
fig.suptitle('3D Realtime Re-modeling',color=color_white) # 设置主标题颜色
ax = fig.add_subplot(111,projection='3d',axisbg=(0.1843,0.3098,0.3098)) # 设置画图区域背景颜色
ax.w_xaxis.set_pane_color(color_bg) # 设置坐标平面颜色
ax.w_zaxis.line.set_lw(0.) # 设置 z 轴线宽(类似语句对 x,y无效)
ax.tick_params(axis='x', colors=color_white) # 设置坐标轴刻度颜色
ax.set_xlabel('x',color=color_red) # 设置坐标轴标签颜色
ax.set_xlim([1,6]) # 设置坐标轴范围
ax.set_yticks(np.linspace(1,4,4)) # 设置坐标轴刻度
ax.set_zticks([]) # 设置坐标轴无刻度
plt.gca().invert_yaxis() # 翻转坐标轴

如果要设置网格线参数,需要在实例化 figure 之前设置如下代码:

from matplotlib import rcParams
rcParams['grid.linestyle'] = '-'
rcParams['grid.color'] = 'g'
rcParams['grid.linewidth'] = 0.5

如果要隐藏所有坐标轴:

ax._axis3don = False
plt.subplot(121)
plt.plot(x_list, y_list)
plt.subplots_adjust(wspace = 0.05, hspace=0.05)

关于 subplots_adjust 的参数说明:

subplots_adjust(left=None, bottom=None, right=None, top=None,
                wspace=None, hspace=None)
left  = 0.125  # the left side of the subplots of the figure
right = 0.9    # the right side of the subplots of the figure
bottom = 0.1   # the bottom of the subplots of the figure
top = 0.9      # the top of the subplots of the figure
wspace = 0.2   # the amount of width reserved for blank space between subplots,
               # expressed as a fraction of the average axis width
hspace = 0.2   # the amount of height reserved for white space between subplots,
               # expressed as a fraction of the average axis height
fig = plt.figure()
fig.savefig('test.png', bbox_inches='tight')
fig = plt.figure()
fig.savefig('test.png', dpi=600)
fig = plt.figure()
fig.savefig('test.svg')

37、numpy 中为矩阵添加一行(列)和在同一行(列)中添加元素

>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> b = np.ones(3)
>>> np.c_[a,b]
array([[ 1.,  2.,  3.,  1.],
         [ 4.,  5.,  6.,  1.],
         [ 7.,  8.,  9.,  1.]])

其实有好几种实现函数,见http://www.tuicool.com/articles/ZVrUjq3

>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.append(np.array([1,2,3]),[4,5,6])
array([1, 2, 3, 4, 5, 6])

38、numpy 中 array 的复制

import numpy as np
a = np.array([[1,2,3]])
b = np.copy()

这一点和 list 不同,对于 list,=不会复制数据,而切片可以。对于 numpy 中的 array,=和切片都不会复制数据,需要copy才可以。
参考http://blog.csdn.net/xidianliutingting/article/details/51682867

39、numpy 中 array 和 matrix 对一维的处理

40、pandas 基本操作

41、超长字符串的声明

42、缺失值(NAN)

43、字典 key 搜索

44、requests 库

import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
上一篇 下一篇

猜你喜欢

热点阅读