第一章 基础知识
- 关于除法
- 1 // 2 → 0
- 1.0 // 2.0 → 0.0
- 1.0 // 2 → 0.0
- 1 / 2 →0.5
- 1.0 / 2.0 → 0.5
- 长整数型和普通整数书写方法一样,只是后面多加了一个L,如10000000000000000L;
- 变量可以由数字、字母和下划线_构成,不能由数字开头;
- print 也是函数,使用方法print(…..)
- 幂函数pow(n,m) → =n**m
- 求绝对值abs(-10) → =10
- 四舍五入round(5.5) → =6
1. 模块
模块相等于python程序的插件,需要使用import来调用,格式为模块.函数,如:
>>>import math >>>math.floor(36.9) 36 >>>math.floor(-36.9) -37 >>>math.ceil(32.2) 33 >>math.ceil(-32.2) -32 #floor()函数为向下取整 ,而ceil(ceiling)函数则为向上取整
import命令的另一种形式,from模块import函数
>>>from math import sqrt >>>sqrt(9) 3.0 #sqrt()函数用于开平方
调用模块中函数的第三种方式:variable = 模块.函数
>>>foo = math.sqrt >>>foo(9) 3.0
模块cmath用于处理虚数,如:
>>>import cmath >>>cmath.sqrt(-1) 1j """cmath(complex math,复数);""" """虚数的书写方法a+bj;""" """此处没有使用from cmath import sqrt的方法,如果这样,则在程序中就不能使用普通的sqrt函数了;"""
2. 字符串
使用反斜杠\ 对字符串中的引号进行转义:
print 'let\'s go' ``` \ 也可用于双引号转义```
字符串的表示,str() & repr() & 两个反引号
- str(),将值转换为字符串,适用于print输出,用户友好;比如str(数字)就不能再参与运算了;
repr()和反引号,把字符串表示为合法的python表达式,比如repr(数字)还可以参与运算;
>>>print repr("hello, world!") 'hello, world!' >>>print str("hello, world!") hello, world! >>>print repr(10000L) 100000L >>>print str(10000L) 10000
input vs raw_input
- input默认输入的是合法的python表达式,如:当需要输入字符串的时候,标准输入应该是”string”
- raw_input只是把输入的数据/值存放到字符串中;
长字符串——①使用三个引号”“”…..”“”此时在长字符串中间可以随意使用单引号和双引号;②使用转义反斜杠\,此时转义\相当于把换行符也转义了;
>>>print "hello, \ world!" hello, world! >>>print """this is a very long string. it continues here. And it's not over yet. """ this is a very long string. it continues here. And it's not over yet.
反斜杠\ 可以用作转义符号,如 \n 可以用作换行命令;
当需要输出反斜杠\ 本身的时候,可以把 \ 当做字符来处理,所以:
>>>print "C:\\python" """前一个反斜杠把后一个转义了""" C:\python
如果字符串中需要输出很多\时,可以使用原始字符串,标志为——r
>>>print r"C:\www.baidu.com 'hello world'" """r后面可以是单引号或双引号;字符串中可以任意含有单引号或双引号;""" C:\www.baidu.com 'hello world'
unicode字符串——用16进制存储的字符串,而原始字符串和长字符串都是8进制表示的字符串;unicode的标示为——u
>>>print u"hello world!" hello world!
第一章小节
本章的新函数
>>>abs(-10) #取绝对值
10
>>>cmath.sqrt(-1) #复数开平方
1j
>>>float("123.45") #将字符串和数字转换为浮点数
123.45
>>>input(prompt)
>>>int(123.45) #将字符串和数字转换为整数
123
>>>long(123.45) #将字符串和数字转换为长整型数
123L
>>>math.ceil(123.4) #向上取整,返回值为浮点数
124.0
>>>math.floor(123.6) #向下取整,返回值为浮点数
123.0
>>>math.sqrt(9) #开平方
3.0
>>>pow(x, y[, z]) #x的y次幂对z取模
>>>pow(2, 3, 7)
1
>>>raw_input(prompt) #从用户获取字符串
>>>repr(object) #返回值的字符串形式
>>>round(number[, ndigits]) #根据给定的精确度四舍五入
>>>round(1.2345, 2)
1.23
>>>str(object) #将值转换为字符串
第二章 列表和元组
1. 概要
- 数据结构→序列[列表、元组、字符串、Unicode字符串、buffer对象、xrange对象]→索引:从零开始计数;
- 列表和元组:两者相似,列表可以修改、元组不能够修改;
列表的创建:
list_name = [1, 2, "apple", "pear", 'movie'] list_name = [[1, 2, 3], ['apple', 'pear', 'banana'], ['Tom', 'Jhon', 'Lily']] #在列表中创建列表
2. 通用序列操作
——包括:
- 索引(indexing)
- 分片(sliceing)
- 加(adding)
- 乘(multiplying)
- 迭代(iteration)——依次对序列中的每个元素重复执行某些操作;
索引——序列中特定元素
- 正向从0计数,逆向从-1开始计数;
- 字符串也可以直接使用索引;
如果函数调用返回的是序列,则可以直接对返回结果进行索引操作;
>>>greeting = 'hello' >>>greeting[1] e >>>greeting[-1] o >>>'hello'[0] h >>>year = raw_input("the year: ")[3] 2015 >>>year '5'
以下是一个从用户获得年月日并输出结果的小程序:
#创建月份列表 month_list = ['Jan', 'Feb','Mar', 'Apr', 'May', \ 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] #创建日期1~31序数词结尾列表 day_ending_list = ['st', 'nd', 'rd'] + 17 * ['th'] + \ ['st', 'nd', 'rd'] + 7 * ['th'] + ['st'] #从用户获得年月日 input_year = raw_input('the year: ') input_month = raw_input('the month: ') input_day = raw_input('the day: ') month_number = int(input_month) day_number = int(input_day) #从列表中调取月份和日期 month_name = month_list[month_number-1] day_name = input_day + day_ending_list[day_number-1] print 'The date you entered is ' + month_name + ' ' + day_name + ', ' + input_year #示例Jan 1st, 2015
分片——调用序列中特定范围内的元素;[n:m]→调用第n到第(m-1)个元素,n小于m,开始点(n)必然包含,而结束边(m)不包含,无论是正向还是逆向;
>>>numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>>numbers[2:6] [3, 4, 5, 6] >>>numbers[:3] #提取第0~第2个元素 [1, 2, 3] >>>numbers[6:9] [7, 8, 9] >>>numbers[6:] #提取第6~结尾的元素 [7, 8, 9] >>>numbers[:] #提取全部元素 [1, 2, 3, 4, 5, 6, 7, 8, 9] >>>numbers[6:-1] [7, 8]
示例:提取url中域名的代码;
#提取形式为http:\\www.XXX.com的url中的域名 url = raw_input("what's your url? ") domain = url[11:-4] print 'The domain is ' + domain
分片进阶——步长,形式[n:m:x]——从第n个到第m-1个元素每隔x-1个元素提取一个元素出来;步长可以为负数,意为从右至左读取;
>>>numbers[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>numbers[0:10:1] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>numbers[0:10:2] [1, 3, 5, 7, 9] >>>numbers[1:9:3] [2, 5, 8] >>>numbers[::4] [1, 5, 9] >>>numbers[9:2:-2] [10, 8, 6, 4]
序列相加——” + “,列表和字符串不能连接——相同类型的序列才能进行连接;
>>>[1,2,3] + [4,5,6] [1,2,3,4,5,6] >>>'hello ' + 'world!' hello, world!
乘法——” * “
>>>3 * 'hello ' hello hello hello >>>3 * ['th'] ['th','th','th']
如何创建一个含有5个元素的列表,而其中不含有任何内容?——None
>>>5 * [None] [None, None, None, None, None]
成员资格——in运算符,检查一个值是否在序列中;条件为真返回True,条件为假返回False;
>>>string = 'hello world!' >>>'h' in string True >>>users = ['Tom', 'Lily', 'Matt'] >>> 'LiMing' in users False >>>setence = "hello word!" >>> "llo" in setence #检测字符串中是否存在字符片段 True
- 检测用户名和密码的程序
#检测输入的用户名和密码是否存在及匹配 database = [ ['Matt', '123'], ['John', '234'], ['Lily', '345'] ] username = raw_input('your name: ') pin = raw_input('your pin: ') if [username, pin] in database: print 'hello ' + username +' !' else: print 'error!!!'
- 检测用户名和密码的程序
长度、最大值、最小值
>>>numbers = [23, 56, 54, 67] >>>len(numbers) 4 >>>max(numbers) 67 >>>min(numbers) 23 >>>max(1,4,6,56,345,97,45) 345
3. 列表:Python的苦力
list函数与join函数
#list从字符串创建列表 >>>list('hello world!') ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] #join从含有字符的列表生成字符串 >>>greeting = ['h', 'e', 'l', 'l', 'o'] >>>''.join(greeting) 'hello' >>>'+'.join(greeting) 'h+e+l+l+o+ +w+o+r+l+d' >>>'\\'.join(greeting) 'h\\e\\l\\l\\o\\ \\w\\o\\r\\l\\d'
基本的列表操作
元素赋值——使用索引为某个特定的、位置明确的元素赋值;不能为一个位置不存在的元素赋值;
>>>name = ['John', 'Tom', 'Lily'] >>>name[1] = 'LiMing' >>>name ['John', 'LiMing', 'Lily']
删除元素——del,为彻底删除;
>>>name = ['John', 'Tom', 'Lily'] >>>del name[1] >>>name ['John', 'Lily']
分片赋值——强大!
功能强大
>>>name = list('John') >>>name[1:] = list('uly') >>>name ['J', 'u', 'l', 'y'] >>>''.join(name) 'July'
分片赋值序列可以与原序列不等长
>>>name = list('Pear') >>>name[1:] = list('ython') >>>name ['P', 'y', 't', 'h', 'o', 'n']
可以在不替换原有元素的情况下,插入新元素或删除元素
>>>name = list('Pear') >>>name[1:1] = list('HHH') #在第1个元素前面插入 >>>name ['p', 'H', 'H', 'e', 'a', 'r'] >>>name[1:3] = [] #删除元素 >>>name ['p', 'e', 'a', 'r']
结合步长等进行复杂操作——不会啊!
列表方法
- 方法与对象(如列表、数字、字符串等)有紧密联系的函数;
- 调用方法:对象.方法(参数)
append——修改原来的列表,而非重新生成有一个;
>>> list_name = [1, 2, 3] >>> list_name.append(4) >>> list_name [1, 2, 3, 4]
count——统计某个元素在列表中出现的次数;
>>> list_name = list('to be or not to be') >>> list_name.count('o') 4 >>> numbers = [[1, 2], 2, 1, [1, 3, [3, 2, 1]]] >>> numbers.count(1) 1 >>> numbers.count([1, 2]) 1
extend——在一个列表的末尾一次性追加另一个序列中的多个值,它修改了原有列表,注意与列表的连接操作,连接操作不改变原有列表;
>>> a = ['a', 'b', 'c'] >>> b = [1, 2, 3] >>> a + b ['a', 'b', 'c', 1, 2, 3] >>> a ['a', 'b', 'c'] #a未被修改 >>> a.extend(b) >>> a ['a', 'b', 'c', 1, 2, 3] #a被extended >>> c = 'hello' >>> a.extend(c) >>> a ['a', 'b', 'c', 1, 2, 3, 'h', 'e', 'l', 'l', 'o']
index——定位列表中的某元素的位置;如果元素有重复呢?如何统计各个有重复元素的个数呢?如何修改或删除重复元素呢?
list_name.index(str, beg, end)
str——指定索引字符串;
beg——开始索引,默认为0;
end——结束索引,默认为字符串长度;>>> list_name = ['This', 'is', 'a', 'list'] >>> list_name.index('list') 3 >>> list_name.index('LIST') Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> list_name.index('LIST') ValueError: 'LIST' is not in list
insert——在第n个元素前面插入元素或列表;
>>> numbers = [1, 3, 4, 5, 6, 9] >>> numbers.insert(3, 'error') >>> numbers [1, 3, 4, 'error', 5, 6, 9]
pop——用于删除特定位置的元素,并返回该元素的值;
栈——类似堆盘子,最后被放入的元素最先被移除——也即后进先出,python语言中的入栈和出栈大概可以由append和pop完成;>>> aList = [123, 'xyz', 'zara', 'abc'] >>> aList.pop() #默认删除最后一个元素 'abc' #返回要删除的值 >>> aList [123, 'xyz', 'zara'] >>> aList.pop(1) #删除第1个值 'xyz' >>> aList [123, 'zara']
#入栈&出栈——后进先出 >>> aList = [123, 'xyz', 'zara', 'abc'] >>> aList.append(aList.pop()) >>>aList aList = [123, 'xyz', 'zara', 'abc'] #——先进先出 >>> aList = ['hello', 123, 'world', 456] >>> aList.insert(0, aList.pop()) #方法1 >>> aList [456, 'hello', 123, 'world'] >>> aList.append(aList.pop(0)) #方法2 >>> aList ['hello', 123, 'world', 456]
remove——移除列表中某个值的第一个匹配项,remove修改了列表,没有返回值;
>>> list_name = ['to', 'be', 'or', 'not', 'to', 'be'] >>> list_name.remove('be') >>> list_name ['to', 'or', 'not', 'to', 'be']
reverse——列表元素反向排列,没有返回值;
>>> list_name = ['to', 'be', 'or', 'not', 'to', 'be'] >>> list_name.reverse() >>> list_name ['be', 'to', 'not', 'or', 'be', 'to']
sort——对列表进行排序,修改了列表,没有返回值!如果要保存原来的列表呢?
>>> x = [1,3,6,4,9,2] >>> y = x.sort() #错误做法,x排序了,但是没有赋值给y; >>> print y None >>> x [1, 2, 3, 4, 6, 9]
>>> x = [1, 5, 2, 7, 4, 8] >>> y = x[:] #正确做法,先复制x >>> print y.sort() #这样的做法也不行!但是此时已经对y列表进行了排序!!! None >>> y [1, 2, 4, 5, 7, 8]
#简单的把x赋值给y是没有用的,因为此时x和y都指向了同一个列表; >>> x = [3, 2, 1] >>> y = x >>> y.sort() >>> x [1, 2, 3] >>> y [1, 2, 3]
另一种获得修改后列表的方法——使用sorted函数
>>> x = [5,7,3,7,2,9] >>> y = sorted(x) >>> x #x未发生改变 [5, 7, 3, 7, 2, 9] >>> y #y是重排过的 [2, 3, 5, 7, 7, 9]
sorted函数的其他用法
>>>sorted('python') ['h', 'n', 'o', 'p', 't', 'y'] #生成列表 >>> sorted('Python') ['P', 'h', 'n', 'o', 't', 'y']
结合reverse函数对列表逆向排列
>>> x = [2, 7, 4, 5] >>> y = sorted(x) >>> y.reverse() >>> y [2, 4, 5, 7] #或者sorted函数和reverse函数连用 x = [2, 7, 4, 5] y = sorted(x).reverse() #书上说可以,不过运行无结果 #错误 y = x.sort().reverse(),因为x.sort()不返回值
高级排序
函数原型:L.sort(cmp=None, key=None, reverse=False)
①cmp参数:cmp接受一个函数,拿整形举例,形式为:
def f(a,b):
return a-b
如果排序的元素是其他类型的,如果a逻辑小于b,函数返回负数;a逻辑等于b,函数返回0;a逻辑大于b,函数返回正数;
②key参数:key也是接受一个函数,不同的是,这个函数只接受一个元素:
def f(a):
return len(a)
key接受的函数返回值,表示此元素的权值,sort将按照权值大小进行排序。
③reverse参数:接受False 或者True 表示是否逆序;>>> cmp(1, 2) -1 >>> cmp(2, 1) 1 >>> cmp(1, 1) 0 >>> numbers = [4, 7, 3, 9] >>> numbers.sort(cmp) >>> numbers [3, 4, 7, 9] >>>
>>> x = ['xdf', 'af', 'dfae', 'hrrdfd'] >>> x.sort(key = len) #按照长度排序 >>> x ['af', 'xdf', 'dfae', 'hrrdfd']
>>> x = list('python') >>> x.sort(reverse = True) #依据reverse值的真假 >>> x ['y', 't', 'p', 'o', 'n', 'h'] >>>
4. 元组:不可变序列
- 元组不能改变;
创建方法:用逗号分隔一些值,即可得到元组,元组大部分时候通过()括起来;
>>> 1,2,3 (1, 2, 3) >>> (1,2,3) (1, 2, 3) >>> 1, (1,) >>> 1 1 >>> 3*(4+5) 27 >>> 3*(4+5,) (9, 9, 9) >>>
tuple函数——以一个序列为参数并将其转换为元组,类似list;
>>> tuple('python') ('p', 'y', 't', 'h', 'o', 'n') >>> tuple([1, 2, 3, [1, 2]]) (1, 2, 3, [1, 2]) >>> tuple((1, 2, 3)) (1, 2, 3) >>> tuple((1,2), [3, 4]) Traceback (most recent call last): File "<pyshell#103>", line 1, in <module> tuple((1,2), [3, 4]) TypeError: tuple() takes at most 1 argument (2 given) >>>
元组的简单操作——操作并不多
>>> x = (3, 2, 2, 'hello', 'python') >>> x[4] #索引 'python' >>> x[4::-2] #分片 ('python', 2, 3) >>> x + x #连接 (3, 2, 2, 'hello', 'python', 3, 2, 2, 'hello', 'python') >>> 2*x #乘法 (3, 2, 2, 'hello', 'python', 3, 2, 2, 'hello', 'python') >>> x #x未被改变 (3, 2, 2, 'hello', 'python') >>> 'hello' in x #成员资格 True >>> len(x) #长度 5 >>> y = sorted(x) #使用sorted生成新的、经过排列的列表 >>> y [2, 2, 3, 'hello', 'python'] >>> y = x[::-1] #使用分片达到reverse的功效 >>> y ('python', 'hello', 2, 2, 3)
元组的不可替代性
- 元组可以在映射中当做键使用,列表不可以;
- 元组是很多内建函数和方法的返回值;
第二章小节
- 序列,一种数据结构;编号;典型的序列包括列表、字符串、元组;列表可修改,字符串和元组不可修改;分片;
- 成员资格——in,返回True or False;可以查找字符串中的字符串;
- 方法
本章新函数
cmp(x, y) #比较大小,返回-1,0,1 len(seq) #返回序列长度 list(seq) #把序列转换为列表 max(args) #返回序列中的最大值 min(args) #返回序列中的最小值 reversed(seq) #对序列进行反向迭代 sorted(seq) #返回已排序的包含seq所以元素的新列表 tuple(seq) #从序列生成元组