资源描述
第一章 快速改造:基础知识
1.2交互式解释器
在IDLE编辑器,在提示符后输入help然后按回车;也可以按下F1获得有关IDLE的帮助信息
1.4数字和表达式
1/2返回0,整除除法;1.0/2返回0.5,用一个或者多个包含小数点的数字参与计算。另外改变除法的执行方式:from_future_import division
//可以实现整除,1.0//2.0返回0.0
%取余数; **幂运算;
>>> 1/2
0
>>> 1.0/2
0.5
>>> 1.0//2.0
0.0
>>> 10%3
1
>>> 9**(1/2)
1
>>> 9**(1.0/2)
3.0
>>> 2.75%0.5
0.25
>>> -9%4
3
>>> -3%2
1
>>> -3/2
-2
1.4.1长整数
普通整数不能大于2147483647也不能小于-2147483648,若更大的数,可以使用长整数。长整数结尾有个L,理论上小写也可以,不过为了便于识别,尽可能用大写。
1.4.2十六进制和八进制
0XAF返回175 ,十六进制;
010返回8,八进制
>>> 0xAF
175
>>> 010
8
1.5变量
包含字母、数字和下划线。首字母不能是数字开头。
1.8函数
Pow计算乘方:pow(2,3),2**3均返回8;pow等标准函数称为内建函数。
Abs(-10)求绝对值,返回10;round(1.0/2.0)返回1.0,把浮点数四舍五入为最接近的整数值。
>>> pow(2,3)
8
>>> 2**3
8
>>> abs(-10)
10
>>> round(1.0/2.0)
1.0
>>> round(8.06,2)
8.06
>>> round(8.06,1)
8.1
1.9模块 import
>>> import math
>>> math.floor(8.8) 向下取整
8.0
>>> math.ceil(8.8)向上取整
9.0
>>> int(math.ceil(32.1))
33
>>> int(32.9)
32
>>> flo=math.floor
>>> flo(33.9)
33.0
使用了from 模块import 函数 ,这种方式的import命令之后,就可以直接使用函数,而不需要使用模块名最为前缀了。但是要注意在不同模块引用,可能导致函数冲突。
>>> from math import sqrt
>>> sqrt(9)
3.0
>>>
1.9.1 cmath和复数 nan-ànot a number返回的结果
Cmath即complex math复数模块
>>> import cmath
>>> cmath.sqrt(-1)
1j
返回的1j是个虚数,虚数以j结尾;这里没有使用from cmath import sqrt,避免与math 的sqrt冲突。
1.10.3注释符号: #
1.11字符串,使用”\”可以进行转义。
1.11.2拼接字符串
>>> 'Hello, ' 'World'
'Hello, World'
>>> 'Hello,' 'World'
'Hello,World'
>>> 'Hello, '+'World'
'Hello, World'
>>> 'Hello, '+5
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
'Hello, '+5
TypeError: cannot concatenate 'str' and 'int' objects
>>>
需要保证两边是一样的字符串,而有其他格式要报错的
1.11.3字符串表示str和repr-à两个均为函数,事实上str是一种类型
Str会将值转换为合理形式的字符串。另外一种是通过repr函数,创建一个字符串。
Repr(x)也可以写作`x`实现(注意:`是反引号),python3.0中已经不适用反引号了
>>> print 'hello,world'
hello,world
>>> print repr('hello,world')
'hello,world'
>>> print str('hello,world')
hello,world
>>> print 1000L
1000
>>> 1000L
1000L
>>> print repr(1000L)
1000L
>>> print str(1000L)
1000
>>> tmp=42
>>> print 'The number is:'+tmp
Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
print 'The number is:'+tmp
TypeError: cannot concatenate 'str' and 'int' objects
>>> print 'The number is:'+`tmp`
The number is:42
>>> print 'The number is:'+str(tmp)
The number is:42
>>> print 'The number is:'+repr(tmp)
The number is:42
1.11.4 input和raw_input的比较
>>> name=input("What's your name:")
What's your name:Gumby
Traceback (most recent call last):
File "<pyshell#60>", line 1, in <module>
name=input("What's your name:")
File "<string>", line 1, in <module>
NameError: name 'Gumby' is not defined
>>> name=input("What's your name:")
What's your name:'Gumby'
后面输入的字符串增加了引号不报错。
>>> input('Enter a number:')
Enter a number:3
3
>>> name=input("What's your name:")
What's your name:'Gumby'
>>> raw_input("What's your name:")
What's your name:Gumby
'Gumby'
>>> raw_input("What's your name:")
What's your name:Gumby
'Gumby'
>>> raw_input('Enter a number:')
Enter a number:3
'3'
>>>
1.11.5长字符串、原始字符串和unicode
(1)长字符串 使用三引号;转义的反斜杠用于行尾
>>> print 'hello, \
world!'
hello, world!
>>> print '''hello,
world!'''
hello,
world!
>>> 1+2+3\
+4
10
(2)原始字符串,对于反斜线并不会特殊对待,以r开头,注意字符串尾部
>>> print 'c:\nowhere'
c:
owhere
>>> print r 'c:\nowhere'
SyntaxError: invalid syntax
>>> print 'c:\nowhere'
c:
owhere
>>> print r'c:\nowhere'
c:\nowhere
>>> print r"This is illegal\"
SyntaxError: EOL while scanning string literal
>>> print r"This is illegal\\"
This is illegal\\
>>> print r"This is illegal" "\\"
This is illegal\
(3)Unicode在字符串前增加前缀U
>>> print u'hello, world'
hello, world
第二章 列表和元组
序列中的每个元素被分配一个序号--à即元素的位置,也被称为索引。第一个索引为‘0’,最后一个元素可以使用-1标记
2.1序列概览
Python包含6中内建的序列:列表,元组,字符串,unicode字符串,buffer对象和xrange对象。
列表和元组的主要区别:列表可以修改,元组则不能。内建函数返回元组。几乎所有情况下都可以使用列表代替元组。特殊情况之一:使用元组作为字典的键,因为键不可以更改,所以不能用列表。
列表的各个元素通过逗号进行分隔,写在方括号内。
>>> edward=['Edward Gumy',42]
>>> john=['John Smith',50]
>>> database=[edward,john]
>>> database
[['Edward Gumy', 42], ['John Smith', 50]]
>>>
2.2通用序列操作
包括:索引,分片,加,乘以及检查某个元素是否属于序列的成员,除此之外还有计算长度,找出最大元素和最小元素的内建函数。
迭代:依次对序列中的每个元素重复执行某些操作。
2.2.1索引
从0开始,最后一个元素可以使用-1.索引访问的单个元素
>>> greeting="Hello"
>>> greeting[0]
'H'
>>> greeting[-1]
'o'
>>> four=raw_input('Year:')[3]
Year:2005
>>> four
'5'
2.2.2分片
冒号:第一个元素包含在分片内,第二个元素不包含在分片内,是分片之后剩余部分的第一个元素编号。
>>> num=[1,2,3,4,5,6,7,8,9,10]
>>> num[3:6]
[4, 5, 6]
>>> num[0:1]
[1]
>>> num[7:10] #索引10指向第11个元素,这个元素不存在。
[8, 9, 10]
>>> num[-3:-1]
[8, 9]
>>> num[-3:0]
[]
>>> num[-3:]
[8, 9, 10]
>>> num[7:]
[8, 9, 10]
>>> num[:3]
[1, 2, 3]
>>> num[:] #复制整个序列
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> num[0:10:2]
[1, 3, 5, 7, 9]
>>> num[3:6:3]
[4]
>>> num[::4]
[1, 5, 9]
>>> num[8:3:-1]
[9, 8, 7, 6, 5]
>>> num[10:0:-2]
[10, 8, 6, 4, 2]
>>> num[0:10:-2]
[]
>>> num[::-2]
[10, 8, 6, 4, 2]
>>> num[5:0:-2]
[6, 4, 2]
>>> num[:5:-2]
[10, 8]
>>> num[5::-2]
[6, 4, 2]
>>>
2.2.3序列相加
两种相同类型的序列才能进行链接操作
>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> 'hello, '+'world'
'hello, world'
>>> 'hello, '+[1,2]
Traceback (most recent call last):
File "<pyshell#122>", line 1, in <module>
'hello, '+[1,2]
TypeError: cannot concatenate 'str' and 'list' objects
>>>
2.2.4乘法
数字X乘以一个序列会生成新的序列,原序列被重复X次
>>> 'PH'*3
'PHPHPH'
>>> [42]*3
[42, 42, 42]
>>> [1,2]*3
[1, 2, 1, 2, 1, 2]
>>> []
[]
>>> [none]*3 #注意N需要大写,不然报错。None是一个内建值,它的含义是“什么也没有”
Traceback (most recent call last):
File "<pyshell#128>", line 1, in <module>
[none]*3
NameError: name 'none' is not defined
>>> [None]*3
[None, None, None]
>>>
2.2.5成员资格 in
检查一个值是否在一个序列中。条件为真返回True,条件未假返回False
>>> pw="abc"
>>> 'a' in pw
True
>>> 'x' in pw
False
>>> database=[['John',42],['Smith',36]]
>>> ['john',42] in database # 大小写,要注意
False
>>> ['John',42] in database
True
>>> num=[1,2,3,4,5]
>>> [1,2] in num
False
>>> [1] in num
False
>>> 1 in num
True
2.2.6 长度、最小值和最大值
内建函数len、min和max
>>> num=[1,8,3]
>>> len(num)
3
>>> max(num)
8
>>> min(num)
1
>>> max(2,3)
3
max 跟min的参数并不一定是序列,而是以多个数字直接作为参数。
>>> exm=['h',12,'e',2]
>>> max(exm)
'h'
>>> exm=[12,'e',2,'h']
>>> max(exm)
'h'
>>> max(['A',1,'1','a','z'])
'z'
这个有点意思了,需要以后注意查查,是根据ascii进行提取的吗?
2.3 列表:Python的“苦力”
讨论列表不同于元组跟字符串的地方
2.3.1 list函数
>>> ls=list("Hello")
>>> ls
['H', 'e', 'l', 'l', 'o']
>>> ''.join(ls)
'Hello'
>>>
2.3.2 基本的列表操作
列表可以使用所有适用于序列的操作。而列表是可以修正的。本节介绍可以改变列表的方法:元素赋值、元素删除、分片赋值以及列表方法(请注意,并非所有的列表方法都真正地改变列表)
1、 改变列表:元素赋值
>>> x=[1,1,1]
>>> x[1]=2
>>> x
[1, 2, 1]
注意:不能为一个位置不存在的元素进行赋值。
2、 删除元素 del
>>> num=[1,2,3,4]
>>> del num[2]
>>> num
[1, 2, 4]
除了删除列表中的元素,del还能用于删除其他元素。可以用于字典元素甚至其他变量的删除操作。
3、 分片赋值
>>> nm=list('perl')
>>> nm
['p', 'e', 'r', 'l']
>>> nm[2:]=list("ar")
>>> nm
['p', 'e', 'a', 'r']
>>> nm[2:]=list("ckly") # 可以改变成长度
>>> nm
['p', 'e', 'c', 'k', 'l', 'y']
>>> nm=[1,5]
>>> nm[1:1]=[2,3,4] # 插入行的元素
>>> nm
[1, 2, 3, 4, 5]
>>> nm[1:4]=[] # 删除一段元素,与del的结果一样
>>> nm
[1, 5]
>>> nm=[1,2,3,4,5]
>>> del nm[1:4]
>>> nm
[1, 5]
可以根据实际步长进行其他操作,测试的时候貌似要注意对应的位置元素个数。
>>> num=[1,2,3,4,5]
>>> num[1:4:2]=[8,10]
>>> num
[1, 8, 3, 10, 5]
2.3.3 列表方法
方法的调用方式: 对象.方法(参数)
1. append 用于在列表末尾追加新的对象,直接修改原来的列表。
>>> lst=[1,2,3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
>>> lst=[1,2,3]
>>> lst.append(4,5)
Traceback (most recent call last):
File "<pyshell#209>", line 1, in <module>
lst.append(4,5)
TypeError: append() takes exactly one argument (2 given)
>>> lst.append([4,5])
>>> lst
[1, 2, 3, [4, 5]]
2. count 方法,统计某个元素在列表中出现的次数:
>>> ['to','be','or','not','to','be'].count('to')
2
>>> x=[[1,2],1,1,[2,1,[1,2]]]
>>> x.count([1,2])
1
3. extend
extend方法可以在列表的末尾一次性追加另一个序列中的多个值。换句话说,可以用新列表扩展原有的列表
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a.extend(b) #extend扩展了原来的序列,即a
>>> a
[1, 2, 3, 4, 5, 6]
>>> a+b #链接操作,仅仅返回一个全新的列表
[1, 2, 3, 4, 5, 6, 4, 5, 6]
>>> a
[1, 2, 3, 4, 5, 6]
>>> a[len(a):]=b #使用分片来实现相同的结果,但是代码的可读性不如extend。
>>> a
[1, 2, 3, 4, 5, 6, 4, 5, 6]
>>> a=a+b #此链接方法的效率要比extend方法低
>>> a
[1, 2, 3, 4, 5, 6, 4, 5, 6, 4, 5, 6]
4. index
index方法用于从列表中找出某个值第一个匹配项的索引位置。
>>> phase=['We','are','hero','!']
>>> phase.index('hero')
2
>>> phase.index('ero')
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
phase.index('ero')
ValueError: 'ero' is not in list
5. insert
用于将对象插入列表中
>>> num=[1,2,3,4,5,6,7]
>>> num.insert(3,'four')
>>> num
[1, 2, 3, 'four', 4, 5, 6, 7]
>>>
>>> num=[1,2,3,4,5,6,7]
>>> num[3:3]='four' #意外发现
>>> num
[1, 2, 3, 'f', 'o', 'u', 'r', 4, 5, 6, 7]
>>> num=[1,2,3,4,5,6,7]
>>> num[3:3]=['four'] #可以分片处理,依然是可读性不如insert
>>> num
[1, 2, 3, 'four', 4, 5, 6, 7]
6. pop
pop方法会移出列表中的一个元素(默认是最后一个),并且返回该元素的值。
pop方法是唯一一个既能修改列表又返回元素值(除了None)的列表方法。
使用pop方法可以实现一种数据结构----栈。对于栈的两个操作(放入和移出),pop跟append方法恰好相反。Python没有入栈方法,变通使用append方法。
提示:对于先进先出的队列,可以使用insert(0,…)来代替append方法。或者,也可以继续使用append方法,但必须使用pop(0)来代替pop().更好的解决方案是使用collection模块中的deque对象。
>>> x=[1,2,3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2]
>>> x=[1,2,3]
>>> x.append(x.pop())
>>> x
[1, 2, 3]
>>>
7. remove
remove方法用于移出列表中某个值的第一个匹配项:
>>> x=['to','be','or','not','to','be']
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']
>>> x.remove('bee')
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
x.remove('bee')
ValueError: list.remove(x): x not in list
注意:remove是一个没有返回值的原位置改变方法。
8. reverse
reverse方法将列表中的元素反方向存放:
>>> x=[1,2,3]
>>> x.reverse()
>>> x
[3, 2, 1]
9. sort
sort方法用于在原位置对列表进行排序。在“原位置排序”意味着要改变原来的列表,从而让其中的元素能按一定的顺序排列,而不是返回一个已经排序的列表副本。
>>> x=[4,6,2,1,7,9]
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]
***************************
>>> x=[4,6,2,1,7,9]
>>> y=x.sort() #因为sort方法修改了x缺返回了空值
>>> print y
None
>>> x
[1, 2, 4, 6, 7, 9]
****************************
>>> x=[4,6,2,1,7,9]
>>> y=x[:] #有效的复制整个列表的方法
>>> y.sort()
>>> x
[4, 6, 2, 1, 7, 9]
>>> y
[1, 2, 4, 6, 7, 9]
***************************
>>> x=[4,6,2,1,7,9]
>>> y=x #简单的赋值是没有用的,仅仅让x跟y都指向同一个列表。
>>> y.sort()
>>> x
[1, 2, 4, 6, 7, 9]
>>> y
[1, 2, 4, 6, 7, 9]
>>>
另外一种获取已排序的列表副本的方法是,使用sorted函数
>>> x=[4,6,2,1,7,9]
>>> y=sorted(x)
>>> y
[1, 2, 4, 6, 7, 9]
>>> x
[4, 6, 2, 1, 7, 9]
>>> sorted('Python') #sorted可以用于任何序列,却总是返回一个列表。
['P', 'h', 'n', 'o', 't', 'y']
如果要把一些元素按照相反的顺序排列,可以先使用sort或者sorted,然后再调用reserse方法,或者使用reverse参数。Sorted(x).reverse()这样可以。
10. 高级排序
如果希望元素按照特定的方式进行排序,可以通过compare(x,y)的方式自定义比较函数。Compare(x,y),x>y 返回正数;x<y返回负数;x=y返回0(根据你的定义)。定义号该函数,可以提供给sort方法作为参数了。内建函数cmp提供了比较函数的默认实现方式:
>>> cmp(42,32)
1
>>> cmp(99,100)
-1
>>> cmp(10,10)
0
>>> num=[5,2,9,7]
>>> num.sort(cmp)
>>> num
[2, 5, 7, 9]
>>> cmp(42,32)
1
>>> num=[5,2,9,7]
>>> num.sort(cmp)
>>> num
[2, 5, 7, 9]
Sort方法还有另外两个参数----key和reverse。如果要使用它们,那么就要通过名字来指定。参数key与cmp类似----必须提供一个在排序过程中使用的函数。然而该函数并不是直接用来确定对象大小,而是为每个元素创建一个键,然后所有元素来排序。那么如果根据元素的长度进行排序,那么使用len作为键函数:
>>> x=['3aaa','1a','4aaaa','0']
>>> x.sort(key=len)
>>> x
['0', '1a', '3aaa', '4aaaa']
另外一个关键字参数reverse是简单的布尔值(True或者false),用来知名列表是否进行反向排序。
>>> num=[5,2,9,7]
>>> num.sort()
>>> num
[2, 5, 7, 9]
>>> num.sort(reverse=True)
>>> num
[9, 7, 5, 2]
>>>
cmp,key,reverse参数都可以用于sorted函数。在多数情况下,为cmp或key提供自定义函数是非常有用的。
2.4 元组:不可变序列
用逗号分隔了一些值,即使仅有一个值,也必须有逗号。
元组跟列表一样,也是一种序列。唯一的不同是元组不能修改。(字符串也是如此)。
创建元组的语法很简单:使用逗号分隔一些值,那么就自动创建了元组。
大部分时候,元组是通过圆括号括起来的。
>>> 1,2,3
(1, 2, 3)
>>> (1,2,3) #大部分时候是通过圆括号括起来的
(1, 2, 3)
>>> ()#空元组
()
>>> 42 #不是元组
42
>>> 42,#必须加个逗号,即时只有一个值
(42,)
>>> (42,)
(42,)
>>> (42) #等同于42,非元组。
42
>>>
2.4.1 tuple函数序列转元组
tuple函数的功能跟list函数基本上一致:以一个序列作为参数并把它转换为元组。如果参数就是元组,那么该参数就会被原样返回。
>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple("abc")
('a', 'b', 'c')
>>> tuple((1,2,3))
(1, 2, 3)
>>> tuple(1,2,3) #注意参数
Traceback (most recent call last):
File "<pyshell#104>", line 1, in <module>
tuple(1,2,3)
TypeError: tuple() takes at most 1 argument (3 given)
>>>
2.4.2 基本元组操作
元组的分片还是元组,就像列表的分片还是列表一样。
除了创建元组和访问元组元素外,也没有太多其他操作,可以参考序列来实现:
>>> x=1,2,3
>>> x[1]
2
>>> x[0:3]
(1, 2, 3)
>>> x[1:1]='c'
Traceback (most recent call last):
File "<pyshell#108>", line 1, in <module>
x[1:1]='c'
TypeError: 'tuple' object does not support item assignment
>>> x=[1,2,3] #序列可以修改
>>> x[1:1]='c'
>>> x
[1, 'c', 2, 3]
>>>
本章函数:
cmp(x,y);len(seq);list(seq);max(args);min(args);
reversed(seq);sorted(seq);tuple(seq)
第三章 使用字符串
本章将介绍如何使用字符串格式化其他的值,并简单了解一下用字符串的分割、连接、搜索等方法能够做哪些。
3.1 基本字符串操作
序列的基本操作(索引,分片,乘法,判断成员资格,求长度,取最小值和最大值)对字符串同样适用,但是字符串是不可以改变的,分片赋值是不合法的。
3.2 字符串格式化:精简版
字符串格式化使用字符串格式化操作符:即百分号%来实现(注意%也可以做去摸运算符)
在%的左侧放置一个字符串(格式化字符串),而右侧则放置希望被格式化的值。
第四章
展开阅读全文