Python基础教程总结(一)

引言:

  一直都听说Python很强大,以前只是浏览了一些博客,发现有点像数学建模时使用的Matlab,就没有深入去了解了。如今Python使用的地方越来越多,最近又在学习机器学习方面的知识,因此想系统的学一学,让心里踏实一点。以下是本人在看《Python基础教程第二版》时,使用自己的思维方式进行的总结,自言自语,把知识串起来,想再使用Python时就少翻点资料。

 

1. 心中有数

  学习一门语言之前我都想知道它到底能干什么,如果它干的事情和我现在已经会的语言相通,可能我就比较着学习,浏览一下语法。先看看百度百科对Python的解释。

  Python(英语发音:/ˈpaɪθən/), 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。常见的一种应用情形是,使用Python快速生成程序的原型(有时甚至是程序的最终界面),然后对其中有特别要求的部分,用更合适的语言改写,比如3D游戏中的图形渲染模块,性能要求特别高,就可以用C++重写。

  可以看出,首先它是一种解释型的脚本语言,因此和Shell之类的很像。其次,它有强大的类库。“类库”,我只对Java熟悉,一听到类库联想到面向对象,类库的另一种理解就是我们可以省去很多的编码工作,使用成熟的类库去解决以前写C或者汇编时一步步实现的一些功能。再次,它的昵称是“胶水语言”。“胶水语言”这个很厉害,让我联想到在JSP文件里面写Java的场景,或者Java调用Native库时的场景,可能比喻得不是很准确,应该和Shell脚本语言比较要贴切点。因此它的“包容”能力巨强,心胸宽广。最后,使用Python快速生成程序的原型。哇,这岂不是验证算法的最好方式。最早我只会C语言,写算法程序的时候还是挺费劲的,从语法上就要考虑怎么能实现这个算法。不知道Python到底能给我带来怎样的便利。

 

2. 第一章——基础知识

2.1. 下载安装

  阅读的这本书是使用的是Python2.5,到Python官网http://www.python.org的Downloads下的All Releases下找一找下一个。

  

2.2. 数字和表达式

  • 对于x = 1/2,在C语言里面会得到0,要想得到0.5,需要有浮点数参与运算,即x = 1.0/2。然后Python也是如此,但是如果希望Python没有浮点数参与就能执行普通除法,需要引入库。
>>> from __future__ import division

 

  但此时又想做整除,怎么办?就要用的//(双斜线) x = 1//2。即使有浮点数参与运算,即x = 1.0 // 2.0,得到的也是0.0;

  • 幂运算: x = 2**3,结果是8。幂运算比取反优先级高,所以x = -3**2,结果是-9,x = (-3)**2结果才是9。或者x = pow(-3,2);
  • 十六进制:0xAF,和C语言一样,前面是0x;
  • 八进制:010,和C语言一样,前面是0;
  • 四舍五入最接近的整数:round();
  • 向下取整:math.floor(32.9),结果是32.0;
  • 复数运算:cmath.sqrt(-1),结果1j;
OperationResult
x | y bitwise or of x and y
x ^ y bitwise exclusive or of x and y
x & y bitwise and of x and y
x << n x shifted left by n bits
x >> n x shifted right by n bits
~x the bits of x inverted

  该运算和C语言类似。

 

2.3. 字符串

  • str()、repr()和反引号(键盘Esc下面带~那个键)是将Python值转换为字符串的3种方式。函数str()让字符串更容易阅读,而repr()和反引号则把结果字符串转换成合法的Python表达式。
  • input()会假设用户输入的是合法Python表达式,raw_input()会把输入当做原始数据。应该尽可能的使用raw_input();
  • 长字符串,且可以换行,可以写在三个引号里面"""Hello Python """;
  • 可以用反斜线(\)换行输入,表示下一行还是一起的;
  • 不加转义,保留原始字符串:print r'c:\Program Files\Python2.5'。即前面加个r;
  • Unicode字符串前加u:u'Hello Python!'

  

3. 第二章——列表和元组

3.1. 概览

  书上说Python包含6种内建序列,常用的是两种类型:列表和元组。但到底是哪6种呢?搜遍了网上的博客,都是前面提到的那句话。最后到官网Document找到了。

 Sequence Types — str(字符串), unicode, list(列表), tuple(元组), buffer, xrange

  序列,是指有序集合排列。所有序列都具有索引(-1是最后一个元素)、分片、加、乘、成员资格、长度、最大和最小的内在函数。列表可以修改,元组则不能。一般情况下,列表都可以替代元组。序列和映射(如字典)是两类主要的容器(container),还有集合(set)也属于容器。

  str,unicode:   这两种字符串前面提到过了;

  list:       列表。如edward = ['Panderen', 12];

  tuple:      元组。

  buffer:      buffer对象,如string, array 和 buffer。使用方式buffer(object[,offset[,size]]);

  xrange:     和range()作用相同,但是xrange返回一个xrange对象。range返回一个list对象。官网文档解释是This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. 也就是说xrange不会把数据同时存起来。相反range会把数据存起来。那range就会开辟很大的空间,特别是数据量很大的时候。因此用xrange也许性能会高点哟。

  下面这个链接把一些常用的类型总结了一下。http://wuyuans.com/2013/04/python-data-type/ 

类型分类类型名称 描述
None Type(None) null对象None
数字类型 int 整数
long 长整数,任意精度(python2)
float 浮点数
complex 复数
bool 布尔值(True或False)
序列类型 str 字符串
unicode Unicode字符串(python2)
list 列表
tuple 元组
xrange xrang()创建的整数范围
映射类型 dic 字典
集合类型 set 可变集合
frozenset 不可变集合

 

 以上都是包括序列在内的常用类型。

 

3.2. 基本运算

OperationResult
x in s True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
s + t the concatenation of s and t
s * n, n * s n shallow copies of s concatenated
s[i] i‘th item of s, origin 0
s[i:j] slice of s from i to j
s[i:j:k] slice of s from i to j with step k
len(s) length of s
min(s) smallest item of s
max(s) largest item of s

  以上是序列的基本通用运算。

 

OperationResult
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) same as s[len(s):len(s)] = [x]
s.extend(x) same as s[len(s):len(s)] = x
s.count(x) return number of i‘s for which s[i] == x
s.index(x[, i[, j]]) return smallest k such that s[k] == x and i <= k < j
s.insert(i, x) same as s[i:i] = [x]
s.pop([i]) same as x = s[i]; del s[i]; return x
s.remove(x) same as del s[s.index(x)]
s.reverse()

reverses the items of s in place

>>> x = [1, 2, 3]
>>> list(reversed(x))
[3, 2, 1]

 

s.sort([cmp[, key[, reverse]]])

sort the items of s in place

x.sort(cmp)

x.sort(key=len),根据长度排序

x.sort(reverse=True),反向排序

  以上是序列的常用操作

3.3. 分片

  开始点包括在返回结果中,结束点不在分片内。

  • number[-3:]  ——  从倒数第三个数开始访问到结尾;
  • number[:]   ——  返回所有,可用于复制序列;
  • number[0:10:1]——  步长为1;
  • number[::4]  ——  每4个元素的第一个;
  • number[8:3:-1] —— 步长为1,从右至左地提取数据;

 

3.4. 乘法

  • 'python'*5,结果是'pythonpythonpythonpythonpython'。相当于复制。
  • None是Python的内建值,表示啥都没有。但却站要站位置。嗯。。。就是站着茅坑不XX。

  

3.5. 列表

  • name = list('hello'),结果是['H','e','l','l','o'];
  • ' '.join(name),结果是"Hello";
  • number[1] = 2,name[2:] = list('ar'),修改值;
  • number[1:1] = [2,3,4],在number[1]前插入2,3,4;
  • number[1:4] = [],代换的方式删除元素,结果和del number[1:4]一样。
  • number.append(object),append是将参数作为对象增加,如
  • 1 >>> number = [1,2,3];
    2 >>> number
    3 [1, 2, 3]
    4 >>> number.append([4,5])
    5 >>> number
    6 [1, 2, 3, [4, 5]]
    7 >>> number.extend([6,7])
    8 >>> number
    9 [1, 2, 3, [4, 5], 6, 7]

  

3.6. 元组

  定义一个包含一个值得元组,x = (42,)。因此会有

>>> 3*(40+2) 
126
>>> 3*(40+2,)
(42, 42, 42)
>>> x = 1, 2, 3
>>> x
(1, 2 ,3)

 

4. 第三章——使用字符串

4.1. 格式化输出

>>> print "Pi is: %.3f" % 3.141592653589793238462643383279
Pi is: 3.142

4.2. 字符串格式化转换类型

FlagMeaning
'#'

The value conversion will use the “alternate form” (where defined below).  

>>> print "Pi is: %#20.3f" % 3.141592653589793238462643383279
Pi is:                3.142
'0'

The conversion will be zero padded for numeric values. 用0填充

>>> print "Pi is: %020.3f" % 3.141592653589793238462643383279
Pi is: 0000000000000003.142
'-'

The converted value is left adjusted (overrides the '0' conversion if both are given). 左对齐

>>> print "Pi is: %-20.3f" % 3.141592653589793238462643383279
Pi is: 3.142
' '

(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.

整数左对齐

>>> print "Pi is: % 20.3f" % -3.141592653589793238462643383279
Pi is:               -3.142
>>> print "Pi is: % 20.3f" % 3.141592653589793238462643383279
Pi is:                3.142
>>> print "Pi is: % 20.3f" % +3.141592653589793238462643383279
Pi is:                3.142
>>> print "Pi is: %+20.3f" % 3.141592653589793238462643383279
Pi is:               +3.142
>>> print "Pi is: %+20.3f" % -3.141592653589793238462643383279
Pi is:               -3.142
'+'

A sign character ('+' or '-') will precede the conversion (overrides a “space” flag).

>>> print "Pi is: %+20.3f" % 3.141592653589793238462643383279
Pi is:               +3.142

 

ConversionMeaning
'd' Signed integer decimal.
'i' Signed integer decimal.
'o' Signed octal value.
'u' Obsolete type – it is identical to 'd'.
'x' Signed hexadecimal (lowercase).
'X' Signed hexadecimal (uppercase).
'e' Floating point exponential format (lowercase).
'E' Floating point exponential format (uppercase).
'f' Floating point decimal format.
'F' Floating point decimal format.
'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.
'G' Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.
'c' Single character (accepts integer or single character string).
'r' String (converts any Python object using repr()).
's' String (converts any Python object using str()).
'%' No argument is converted, results in a '%' character in the result.

 

先写到这里,看看书再继续写字典,条件语句,类,异常。。。

posted on 2014-09-20 10:38  Panderen  阅读(711)  评论(0编辑  收藏  举报

导航