目录
文章目录
- 目录
- 第0章 ubuntu进入、退出python
- 0.0 一波操作
- 1)argv 接受终端参数(字符串)
- 2)exists 文件是否存在
- 3)判断数字范围in range()
- 4)python中1不等于true,-1也不等于false
- 5)注释、中文不通过?
- 6) 别随意用()啦
- 7)获取函数用法help()
- 8)获取变量类型type()
- 9)if ______name__ == ______'main'__:
- 0.1 ubuntu进入、退出python
- **进入**
- 退出
- 0.2 终端查询函数用法
- 第1章 输入输出
- 1.1 输出
- 打印中文\写注释
- 格式化输出
- 连接字符
- 换行、制表
- 单引号、双引号、三引号
- print后加,的作用
- 1.2 输入
- input()和raw_input()的区别
- 第2章 模块(库)、解包
- argv
- 第3章 读、写文件
- 3.1 常见命令
- 不用close的写法
- 3.2 读
- read()
- readlines()
- 3.3 写
- seek()
- 3.4 更多
- 3.5 pickle
- 3.5.1 存
- 3.5.2 取
- 3.5.2 取
- 第4章 函数
- 4.1 构建
- 4.2 变量作用域
- 4.2.1 全局变量
- 4.3.2 局部变量
- 4.3.3 同名变量 (优先局部)
- 4.3 返回值
- 4.4 特殊函数
- 4.4.1 递归(谨慎)
- 4.4.2 特殊函数
- (1)lambda
- (2)map
- (3)reduce
- (4)filter
- (5)yield(待补充)
- 第5章 逻辑语句
- 5.1 if、elif、else
- 5.2 for 循环
- 5.3 while
- 5.4 continue,break
- 5.5 迭代方法
- 方法一
- 方法二
- 第6章 序列(字符串、列表[]、元组(tuple))
- 6.0 认识序列
- 6.0.1 通用操作
- 6.0.2 常用方法
- 6.1 字符串
- 6.1.1 常用方法
- **6.1.2 详细示例**
- 6.2 列表
- 6.2.1 常用方法
- 6.2.2 详细示例
- 6.3 元组
- 6.3.1 常用方法
- **6.3.2 打包与解包**
- 打包
- 整个序列作为tuple元素
- 多个序例元素一一对应
- 6.4 注意
- 第7章 字典{dict:dict}
- 需要有序字典?
- 第8章 集合{set}
- 第9章 模块、类、对象
- 9.1 什么是模块?
- 与类的区别?
- 9.2 类与对象
- 9.2.1 实例化
- 9.2.2 几个例子
- 9.2.3 与c++的区别
- 9.3 类详解
- 9.3.1 定义
- 方法一
- 方法二
- 9.3.2 初始化(与构造函数有些不同)
- 9.3.3 类中函数
- 9.3.4 函数注释
- 9.3.5 调用
- 对象调用类里变量/函数
- 类内调用自身/父类的变量/函数
- 9.4 类属性和实例属性
第0章 ubuntu进入、退出python
0.0 一波操作
1)argv 接受终端参数(字符串)
from sys import argv
script,first,second,third=argv
print "The script is called:",script
print "The first variable is:",first
print "The second variable is:",second
print "The third variable is:",third
终端:
$ python2.7 first second third
2)exists 文件是否存在
from import exists
...
exists(file)
3)判断数字范围in range()
注意,其实range是左闭右开,如
def judge_1():
if a in range(1,10): #注意这里是(1,10)而不是(0,10)
print "a in range(0,10)"
else:
print "a<0 or a>10"
a=0
judge_1()
a=10
judge_1()
-
结果:
a<0 or a>10
a<0 or a>10
4)python中1不等于true,-1也不等于false
5)注释、中文不通过?
# -*- coding:utf-8 -*-
6) 别随意用()啦
python的()多了一个打包元组的含义
7)获取函数用法help()
自定义类、函数可以使用文档字符串“”“添加注释,使得内容可以通过help()获得。
8)获取变量类型type()
9)if ____name == ____‘main’:
一个python的文件有两种使用的方法,第一是直接作为脚本执行,第二是import到其他的python脚本中被调用(模块重用)执行。因此if ____name == ____‘main’: 的作用就是控制这两种情况执行代码的过程,在if ____name == ____‘main’: 下的代码只有在第一种情况下(即文件作为脚本直接执行)才会被执行,而import到其他脚本中是不会被执行的。
0.1 ubuntu进入、退出python
进入
终端
python #进入默认python版本
python2.7 #进入指定版本
运行已有程序
python
python2.7
退出
quit()
0.2 终端查询函数用法
pydoc
注意:要在终端使用,而不是python内。
pydoc raw_input
pydoc open
退出pydoc
输入q
第1章 输入输出
1.1 输出
打印中文\写注释
在代码开头加上
# -*- coding:utf-8 -*-
格式化输出
单个
>>> print "Hey %s there" % "you"
Hey you there
多个用()
>>> print "Do %s know who %r am?" % ('you' ,'I' ) #%r表示原始数据值,但无法打印非ASCII码,而且会使转移字符失效
Do you know who 'I' am?
%r
>>> print "我的%r" % '天' #%r无法打印非ASCII码
我的'\xe5\xa4\xa9'
连接字符
>>> print 'S'+'.H.'+'E'
S.H.E
换行、制表
换行
>>> print "a\nb"
a
b
>>> print " a \n b \n c "
a
b
c
制表
>>> food_list="""
... \t* Chocolate
... \t* Cookie
... \t* Ice cream\n\t* pudding"""
>>> print food_list
* Chocolate
* Cookie
* Ice cream
* pudding
单引号、双引号、三引号
出现相同符号时都要用\转义;同时三引号可以用于多行注释
>>> print 'say \'hello\''
say 'hello'
>>> print "say \"hello\""
say "hello"
>>> print '''
... say
... \'''hello\'''
... '''
say
'''hello'''
print后加,的作用
输出在同一行,但是python3该方法失效
加,
print "How old are you",
age=raw_input()
print "How tall are you",
height=raw_input()
print "So,you're %r old and %r tall." % (age,height)
-
结果:
How old are you 32
How tall are you 186
So,you’re ‘32’ old and ‘186’ tall.
不加,
print "How old are you"
age=raw_input()
print "How tall are you"
height=raw_input()
print "So,you're %r old and %r tall." % (age,height)
-
结果
How old are you
32
How tall are you186
So,you’re ‘32’ old and ‘186’ tall.
1.2 输入
input()和raw_input()的区别
raw_input()把输入的都当作字符串,而input()输入什么类型就是什么类型;raw_input()可以在括号内用“”提供提示,并仅将用户输入的数赋给变量。
age=raw_input("How old are you?: ")
print "How tall are you?:",
height=raw_input()
print "So,you're %r old and %r tall." % (age,height)
可以把输入提示符赋给变量,这样就不用一直打啦~
prompt=">Your answer here['Y' or 'N']:"
print "Do you want to go skateboard?"
want=raw_input(prompt)
print "Do you like it?"
like=raw_input(prompt)
if like[0]==('Y' or 'y'): #这里的()千万不能丢,不然结果永远是True
like1=''
else:
like1='don\'t '
print '''
So,you said %s about going skateboard.
And you %slike it.
''' % (want,like1)
-
结果
Do you want to go skateboard?
Your answer here[‘Y’ or ‘N’]:n
Do you like it?
Your answer here[‘Y’ or ‘N’]:nSo,you said n about going skateboard.
And you don’t like it.
第2章 模块(库)、解包
argv
新建一个,内容如下
from sys import argv
script,first,second,third=argv
print "The script is called:",script
print "The first variable is:",first
print "The second variable is:",second
print "The third variable is:",third
在终端将四个参数传入后,结果如下:
$ python2.7 a b c
The script is called: practice.py
The first variable is: a
The second variable is: b
The third variable is: c
-
argv与raw_input()的区别:
argv:需要在命令行获得参数;
raw_input():脚本执行过程中获得参数;
-
命令行输入的参数是字符串!可以用int()转化为整数
第3章 读、写文件
3.1 常见命令
- close – 关闭文件。
- read – 读取文件内容。可以把结果赋给一个变量。
- readline(n) – 读取文本文件中的一行,n为可读入的最长字节数
- readlines – 将以列表的形式返回该文件中包含的所有行,列表中的一项表示文件的一行。
- truncate – 清空文件,谨慎使用!
- write(‘stuff’) – 将stuff写入文件。
- name – 返回文件名称。
- seek(offset,whence=0) – 操作文件游标移动,offset正负表示方向;whence=0:从文件开头开始算起,1:当前位置,2:文件末尾。
- tell – 返回文件中的位置
open
open(name[, mode[, buffering]])
mode
- r – 只读
- w – 只写(清空原有,没有文件则创建)
- a – 追加
- 修饰符+:同时读写
序号 | 模式 | 描述 |
---|---|---|
1 | r | 只读模式打开文件,文件的指针在文件开头,即从第一行第一列读取文件内容 |
2 | rb | 在二进制格式下以只读模式打开文件,,文件指针放在开头,即从第一行第一列读取文件内容 |
3 | r+ | 读写模式打开文件,文件指针在开头 |
4 | rb+ | 在二进制格式下以读写模式打开文件,文件指针在文件开头 |
5 | w | 以写模式打开文件,文件指针在文件开头,即从文件头开始编辑,原有内容被删除,如果文件不存在,会自动创建文件 |
6 | wb | 在二进制格式下以写模式打开文件,如果文件存在,从头开始编辑,原有内容被删除,文件不存在,自动创建文件 |
7 | w+ | 读写模式打开文件,文件存在,从头开始编辑,原有内容被删除,文件不存在,自动创建文件 |
8 | wb+ | 在二进制格式下以读写模式打开文件,从头开始编辑,原有内容被删除,文件不存在则自动创建文件 |
9 | a | 打开文件追加内容,如果文件存在,文件指针放在文件结尾,即继续先前的文件继续编辑,文件不存在,自动创建文件 |
10 | ab | 在二进制格式下追加文件内容,文件指针放在文件结尾,即继续先前的文件继续编辑,文件不存在,自动创建文件 |
11 | a+ | 以读写模式追加文件内容,文件指针在文件结尾,即继续先前的文件继续编辑,文件不存在,自动创建文件 |
12 | ab+ | 在二进制格式下追加文件内容,文件指针在文件结尾,即继续先前的文件继续编辑,文件不存在,自动创建文件 |
不用close的写法
with open(filename) as f:
3.2 读
read()
from sys import argv
script,filename=argv
text=open(filename)
print "Here's your file %r:" % filename
print text.read()
text.close()
print "Type your file again:"
file_again=raw_input("> ")
text_again=open(file_again)
print text_again.read()
text_again.close()
结果:
$ python2.7
Here's your file '':
This is stuff I types into a file.
It is really cool stuff.
Lots and lots of fun here.
Type your file again:
>
This is stuff I types into a file.
It is really cool stuff.
Lots and lots of fun here.
readlines()
txt内容为:
1
2
3
4
5
6
from sys import argv
script,filename=argv
def try_readlines(filename):
f=open(filename)
lines=f.readlines()
#i=0
#while i<len(lines):
#print(lines[i]),
#i=i+1
#print "over!"
for line in lines:
print(line), #注意这里的,
print "over!"
f.close()
try_readlines(filename)
结果:
$ python2.7
1
2
3
4
5
6
over!
【注意】
-
如果备注位置没有加
,
则结果为1
2
3
4
5
6
over!
因为列表每一项结尾会换行;每一次print函数执行后也会i换行,相当于换行了两次。加了逗号相当于告诉print不要换行。
3.3 写
txt内容为:
a
b
c
from sys import argv
script,filename=argv
print "We're going to erase %r." % filename
raw_input('?')
print "Opening ..."
target=open(filename,'w')
print "Bye bye,truncating %r!" % filename
target.truncate()
print "Now,put three new sentences:"
line1=raw_input('line1:>')
line2=raw_input('line2:>')
line3=raw_input('line3:>')
print "I'm going to write them to the file."
target.write(line1+'\n')
target.write(line2)
target.write('\n')
target.write(line3)
target.write('\n')
print "Let me see the new content."
target.close()
target=open(filename)
print target.read()
print "Check!Now close it."
target.close()
结果:
$ python2.7
We're going to erase ''.
?
Opening ...
Bye bye,truncating ''!
Now,put three new sentences:
line1:>a
line2:>b
line3:>c
I'm going to write them to the file.
Let me see the new content.
a
b
c
Check!Now close it.
【注意】
- 最后一个代码块中,一定要重新close()后再open()一遍,不然不会显现出abc
$ python2.7
We're going to erase ''.
?
Opening ...
Bye bye,truncating ''!
Now,put three new sentences:
line1:>a
line2:>b
line3:>c
I'm going to write them to the file.
Let me see the new content.
Check!Now close it.
seek()
建立一个txt,内容为
123456'a''b'cdefg
脚本代码为:
# -*- coding:utf-8 -*-
from sys import argv
script,filename=argv
def try_seek(filename):
with open(filename) as f:
f.seek(0,2)#将文件游标移动到文本最末
end=f.tell()#记录文本末游标位置
f.seek(0)
print "file bytes=%r"%end
seek=0#设置一个外部变量(作用域问题)记录游标位置
while True:
print f.readline(2),#每次最多从文件游标位置开始向后读取两个字节
seek=f.tell()#记录当前游标位置
if seek==end:
print "tab over!"
break #break只会跳出当前while循环
#return #return则会直接跳出当前seek函数
print "close file over!"
try_seek(filename)
结果:
$ python2.7
file bytes=18
12 34 56 ‘a ‘’ b’ cd ef g
tab over!
close file over!
【注意】
- 注意,如果用的return则不会有最后一句话close file over!
3.4 更多
复制一个文件内的内容到另一个:
from sys import argv
from os.path import exists
script,source_file,target_file=argv
in_file=open(source_file)
in_data=in_file.read()
print "The input file is %d bytes long" % len(in_data)
print "Does the target file exist? %r" % exists(target_file)
print "Now,copy data from source file to the target file..."
out_file=open(target_file,'w')
out_file.write(in_data)
print "Finish."
out_file.close()
in_file.close()
简化版:
from sys import argv
from os.path import exists
#script,source_file,target_file=argv
open(argv[2],'w').write(open(argv[1]).read())
使用echo命令给source_file中输入测试文字:
$echo "This is a test." >
结果:
$ python2.7
The input file is 6 bytes long
Does the target file exist? False
Now,copy data from source file to the target file…
Finish.
- 使用形如indata=open(file).read()时,就不用另外写一句()了,因为执行完这一句以后。文件会自动关闭。
3.5 pickle
import pickle
3.5.1 存
-
开
文件变量=open("文件路径目标名",'wb')
-
存
(data,文件变量)
-
关
文件变量.close()
3.5.2 取
-
开
文件变量=open("文件路径目标名",'wb')
-
取
data=(文件变量)
-
关
文件变量.close()
3.5.2 取
第4章 函数
4.1 构建
使用def
新建函数
def print_two(*args):
arg1,arg2=args #解包
print "arg1:%r,arg2:%r" % (arg1,arg2) #不需要\n换行,执行下一个函数时就会自动换行了
def print_two_again(arg1,arg2):
print "arg1:%r,arg2:%r" % (arg1,arg2)
def print_none():
print "nope..."
print_two("cake!","cookie!!")
print_two_again("cake!","cookie!!")
print_none()
结果:
arg1:‘cake!’,arg2:‘cookie!!’
arg1:‘cake!’,arg2:‘cookie!!’
nope…
【注意】
-
*args
中的*****用于告诉python把函数的所有参数组织在一个列表放在args
里,类似函数里的argv。
4.2 变量作用域
函数里面的变量和脚本里面的变量是没有关系的。
4.2.1 全局变量
(1) 函数外定义的变量
glob_str="Hello "
def foo():
local_str="world!"
print glob_str+local_str
foo()
Hello world!
4.3.2 局部变量
4.3.3 同名变量 (优先局部)
全局变量和局部变量用同一个名字。
-
如果存在同名变量,函数内会使用哪个?
a = 3 def f(): a = 5 print(a ** 2) f()
25
答:局部变量而不是全剧变量。
-
可否在函数中改变全局变量的值?
-
答:可以,但要在函数内先global a,强调a为全局变量,不然会报错。
def f(x): print(a) a = 5 print(a + x) a = 3 f(8)
UnboundLocalError: local variable ‘a’ referenced before assignment
global
def f(x): global a print(a) a = 5 print(a + x) a = 3 f(8) print(a)
3
13
5
4.3 返回值
def add(*added)
a,b=added
return a+b
def subtract(a,b)
return a-b
a=5
b=3
print "I have %d apples, you have %d apples, so we have %d apples" % (a,b,add(a,b))
print "I have %d apples,eat %d apples, so I have %d apples NOW" % (a,b,subtract(a,b))
结果:
$ python2.7
I have 5 apples, you have 3 apples, so we have 8 apples.
I have 5 apples,eat 3 apples, so I have 2 apples now.
4.4 特殊函数
4.4.1 递归(谨慎)
以著名的斐波拿起数列为例:
# coding=utf-8
meno={0:0,1:1} #字典
def fib(n):
if not n in meno:
meno[n]=fib(n-1)+fib(n-2)
return meno[n]
if __name__=="__main__": #确保代码只有在作为脚本运行(而不是被作为模块import)时才会执行。
f=fib(10)
print f
55
4.4.2 特殊函数
(1)lambda
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a7bE1F3r-1608705150131)(图像/2020-08-27 09-27-03 的屏幕截图-)]
函 数 名 = l a m b d a 参 数 1 [ , 参 数 2 [ . . . ] ] : 表 达 式 函数名=lambda\ 参数1[,参数2[...]]:表达式 函数名=lambda 参数1[,参数2[...]]:表达式
- lambda只能有一个表达式,且不能包含print类的命令。
【例子】
有一个如下代码:
def add(x):
x+=3
return x
numbers=range(10)
new_numbers=[]
for i in numbers:
new_numbers.append(add(i))
print new_numbers
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
当然也可以写成
numbers=range(10)
new_numbers=[i+3 for i in numbers]
print new_numbers
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
如果用lambda:
add=lambda x:x+3
numbers=range(10)
new_numbers=[add(i) for i in numbers]
print new_numbers
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
lambda更可以用于只需要执行一次的函数:
print (lambda x,y:x**y)(4,2) #4^2=16
16
不同的lambda函数甚至可以作为元素存储在list’中
lambs=[lambda x:1,lambda x:x,lambda x:x**2,lambda x:x**3,lambda x:x**4]
print "put in a number please:"
num=int(raw_input())
for index,lamb in enumerate(lambs):
print "%d^%r=%r" % (num,index,lamb(num))
put in a number please:
5
5^0=1
5^1=5
5^2=25
5^3=125
5^4=625
(2)map
m a p ( f u n c t i o n , s e q [ , s e q [ . . . ] ] ) map(function,seq[,seq[...]]) map(function,seq[,seq[...]])
执行时,序列seq中每个对象都会被掏出来执行function,并将返回值存入一个列表中。
numbers=range(10)
new_numbers=map(lambda x:x+3,numbers)
print new_numbers
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
def add(x):return x+3
numbers=range(10)
new_numbers=map(add,numbers)
print new_numbers
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
复杂练习
如果想把几个人的几项信息分别放在不同列表里,想要打印每个人的信息怎么办?
def info(x,y,z):
print "%s's %r years old,and tall %d" % (x,y,z)
names=['Annie','Bonnie','Jack','Pennie']
ages=[15,16,15,14]
height=[165,162,187,157]
map (info,names,ages,height)
Annie’s 15 years old,and tall 165
Bonnie’s 16 years old,and tall 162
Jack’s 15 years old,and tall 187
Pennie’s 14 years old,and tall 157
(3)reduce
r e d u c e ( f u n c t i o n , i t e r a b l e [ , i n i t i a l i z e r = N o n e ] ) reduce(function,iterable[,initializer=None]) reduce(function,iterable[,initializer=None])
如果说map是对几个列表进行上下运算,reduce就是对东西进行横向逐个运算:
直接上例子:
print reduce(lambda x,y:x+y,[1,2,3,4,5])
15
复杂练习
a=[3,9,8,5,2]
b=[1,4,9,2,6]
计算:a[0]*b[0]+a[1]*b[1]…
老方法:
a=[3,9,8,5,2]
b=[1,4,9,2,6]
print "zip:",zip(a,b)
new_list=[x*y for x,y in zip(a,b)]
print new_list
print sum(new_list)
zip: [(3, 1), (9, 4), (8, 9), (5, 2), (2, 6)]
[3, 36, 72, 10, 12]
133
reduce
方法1
a=[3,9,8,5,2]
b=[1,4,9,2,6]
print "zip:",zip(a,b)
print reduce(lambda sum,(x,y):sum+x*y,zip(a,b),0) #以零为初始值,先把0传递给lambda作为sum,再传递zip中的一个元组
zip: [(3, 1), (9, 4), (8, 9), (5, 2), (2, 6)]
133
方法2
from operator import add,mul
reduce(add,map(mul,a,b))
133
方法3
a=[3,9,8,5,2]
b=[1,4,9,2,6]
print reduce(lambda x,y:x+y,map(lambda x,y:x*y,a,b),0)
133
(4)filter
f i l t e r ( f u n c t i o n , i t e r a b l e ) filter(function,iterable) filter(function,iterable)
filter,原意为过滤器,iter中只有使function返回true的元素会被留下。
直接上代码:
numbers=range(-5,6)
print numbers
print "filter:",filter(lambda x : x>0,numbers)
print "source_list:",numbers
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
filter: [1, 2, 3, 4, 5]
source_list: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
(5)yield(待补充)
第5章 逻辑语句
5.1 if、elif、else
def judge_1():
if a==1:
print "a=1"
elif a==2:
print "a=2"
elif a in range(1,10): #注意这里是(1,10)而不是(0,10)
print "a in range(0,10)"
else:
print "a<0 or a>10"
a=1
judge_1()
a=2
judge_1()
a=3
judge_1()
a=0
judge_1()
a=10
judge_1()
a=1
a=2
a!=1 or 2
- 注意range是左闭右开的。
5.2 for 循环
for循环除了c语言常用的i<num模式外,还提供了更简单的循环方式:for obj in objs。其中objs为一个列表(list=[1,2,‘a’,[a,b,c]])
以之前的例子为例:
1
2
3
方法一(列表):
from sys import argv
script,filename=argv
def try_readlines(filename):
with open(filename) as f:
f=open(filename)
lines=f.readlines()
for line in lines:
print(line), #注意这里的,
print "over!"
try_readlines(filename)
方法二(老思路):
from sys import argv
script,filename=argv
def try_readlines(filename):
with open(filename) as f:
lines=f.readlines()
i=0
while i<len(lines):
print(lines[i]),
i=i+1
print "over!"
try_readlines(filename)
5.3 while
i=0
while i<10:
i+=1
print i
1
2
3
4
5
6
7
8
9
10
5.4 continue,break
continue:结束该次循环进入下一次循环
break:结束当前整个循环
5.5 迭代方法
- 循环(loop) – 满足某种条件下,重复执行某一动作,如while
- 迭代(iterate) – 按照某种顺序逐一访问对象中的每一项,如for
- 递归(recursion) – 指的是一个函数不断调用本身
- 遍历(traversal) – 指的是按照一定顺序访问树形结构每个节点,且只访问一次
方法一
for i in list:
方法二
lst=['oh',',','my',' god']
lst_iter=iter(lst)
while True:
print lst_iter.next()
oh , my god
Traceback (most recent call last):
File “”, line 4, in
print lst_iter.next(),
StopIteration
第6章 序列(字符串、列表[]、元组(tuple))
6.0 认识序列
序列包括字符串、列表、元组。字符串可以看作字符的序列,列表是不同类型数据组合的序列。
元组与列表的区别是什么?元组不允许修改和新增元素。
6.0.1 通用操作
- seq[start:end] – 切片
- “+” – 连接两个序列
- “*” – 重复组合序列数据
- in、not in – 判断元素是否在序列里
【示例】
l1=[1,2,3,4,5,6]
l2=['a',1,2,7,8,9,10]
l2=l2[1:]
if 'a' not in l2:
print l2
print l1+l2
print l1*2
[1, 2, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 1, 2, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
6.0.2 常用方法
- list(iter) – 将可迭代对象转换成列表,即会改变该iter
- tuple(iter)
- str(obj)
- len(seq) – 返回seq的长度
- enumerate(iter[,start]) – 返回一个enumerate对象,可生成一个迭代器,元素为iter的元素+索引组成的元组
- zip(iter1[,iter2[…]]) – 返回一个zip对象,可生成一个迭代器,其第n个元素为每个迭代器对象的第n个元素组成的元组
- sorted(iter,key,reverse) – 可通过key指定排序依据;reserve决定是否逆序排列;可参照序列的sort
- reversed(seq) – 与()不同,该操作不会影响list本身,只会返回逆序后的序列
- sum(iter,start) – 将iter中的数值都加上一个start,返回float类型
- max(iter)
- min(iter)
【示例】
enumerate
模拟成绩排名系统输出:
score_range=['Annie','Bonnie','Jack','Pennie']
for index, item in enumerate(score_range):
print "The %r place is %r!Congratulation!" % ((1+index), item)
print "list the enumerate:%r"%list(enumerate(score_range))
The 1 place is ‘Annie’!Congratulation!
The 2 place is ‘Bonnie’!Congratulation!
The 3 place is ‘Jack’!Congratulation!
The 4 place is ‘Pennie’!Congratulation!
list the enumerate:[(0, ‘Annie’), (1, ‘Bonnie’), (2, ‘Jack’), (3, ‘Pennie’)]
zip+sum+reversed+sorted+max+len
模拟排名+学号+姓名+成绩输出系统(其中排名根据成绩计算):
# -*- coding:utf-8 -*-
#对成绩进行正序排列
def score_comp(x,y):
if x>y:
return 1
elif x<y:
return -1
else:
return 0
#按照成绩将信息进行正序排列,成绩好的在后
def tup_info_comp(x,y):
score1=x[2]
score2=y[2]
if score_comp(score1,score2)==1:
return 1
elif score_comp(score1,score2)==-1:
return -1
else:
return 0
number_range=[3,1,2,4,10]
name_range=['Annie','Bonnie','Jack','Pennie','Carolin']
score_range=[83,67,74,68,98]
#利用zip获得包含每个人信息的元组列表
range_list=zip(number_range,name_range,score_range)
print "The list is:%r" % range_list
#排序
range_list2=sorted(range_list,tup_info_comp)
#由于是正序排列,所以成绩好的反而排在后面了,我们逆转一下
range_list2=reversed(range_list2)
#利用enumerate函数获得排序好后代表排名的index
for index, info_tup in enumerate(range_list2):
number,name,score=info_tup
print "The %r place is number%r %r,your score is %r!Congratulation!" % ((1+index), number,name,score)
#for bumber,name,score in zip(number_range,name_range,score_range):
#print "The %r place is %r!Congratulation!" % ((1+index), item)
print "The best score is %r,the average is %r!" % (max(score_range),sum(score_range,20)/len(score_range))
The list is:[(3, ‘Annie’, 83), (1, ‘Bonnie’, 67), (2, ‘Jack’, 74), (4, ‘Pennie’, 68), (10, ‘Carolin’, 98)]
The 1 place is number10 ‘Carolin’,your score is 98!Congratulation!
The 2 place is number3 ‘Annie’,your score is 83!Congratulation!
The 3 place is number2 ‘Jack’,your score is 74!Congratulation!
The 4 place is number4 ‘Pennie’,your score is 68!Congratulation!
The 5 place is number1 ‘Bonnie’,your score is 67!Congratulation!
The best score is 98,the average is 82!
6.1 字符串
6.1.1 常用方法
- format(*args,**kwargs) – 格式化字符串
- count(sub[start,[end]) – 计算sub在指定位置中出现的次数
- find(sub[,start[,end]) – 返回制定字符在指定位置中出现的索引;找不到返回-1(索引是绝对的,与start从哪开始无关)
- index(sub[,start[,end]) – 返回制定字符在指定位置中出现的索引;找不到报错ValueError(索引是绝对的,与start从哪开始无关)
- replace(old,new[,count]) – 将old换成new,如果有count,仅仅替换前count次
- lstrip([chars]) – 移除字符串中左边字符串包含的字符(注意不是字符串),返回移除后生成的新字符
- rstrip([chars]) – 移除字符串右边指定字符,返回移除后生成的新字符
- strip([chars]) – 移除字符串头尾边指定字符,返回移除后生成的新字符
- join(iterable) – 用指定字符串s连接元素为字符串的可迭代对象
- split(sep=None,maxsplit=-1) – 用指定字符串(默认为空格+换行府等)作为分隔符分隔s,maxsplit为分隔次数(默认不限次数),返回list
- endswith(suffix[,start[,end]) – 判断字符串是否以suffix结尾
- startswith(suffix[,start[,end]) – 判断字符串是否以suffix结尾
- upper – 字符全部转化为大写
- isupper – 判断字符是否全部为大写
- lower
- capitalize – 将字符串首字母大写
- title – 将字符串每个单词首字母大写
- 上述所有更改操作均不会改变对象本身
6.1.2 详细示例
count
s="abaacdaaaaeaaaf"
print "S has %r a." % s.count('a')
S has 10 a.
find
a="abcdefghi"
print "d index is %r." % a.find('d',1)
d index is 3.
replace
s="abaacdaaaaeaaaf"
print "s=%r" % s
s1=s.replace('a','h',4)
print "s1=('a','h',4)\n\ts=%r\n\ts1=%r" %(s,s1)
s=‘abaacdaaaaeaaaf’
s1=(‘a’,‘h’,4)
s=‘abaacdaaaaeaaaf’
s1=‘hbhhcdhaaaeaaaf’
strip
s=" abaacdaaaaeaaafaacc"
print "s=%r" % s
s1=s.strip(' ac')
print "s1=s1=(' ac')\n\ts=%r\n\ts1=%r" %(s,s1)
s=’ abaacdaaaaeaaafaacc’
s1=s1=(’ ac’)
s=’ abaacdaaaaeaaafaacc’
s1=‘baacdaaaaeaaaf’
join
s=' '
words=['How','are','you']
print s.join(words)
How are you
split
sentence='''What a nice day!
Let's go out and play!
And get ourselves a cup of milk-tea!'''
print "()=\"%r\"\n" % sentence.split()
print "('\n',1)=\"%r\"\n" % sentence.split('\n',1)
结果:
()="[‘What’, ‘a’, ‘nice’, ‘day!’, “Let’s”, ‘go’, ‘out’, ‘and’, ‘play!’, ‘And’, ‘get’, ‘ourselves’, ‘a’, ‘cup’, ‘of’, ‘milk-tea!’]"
(’ ',1)="[‘What a nice day!’, “Let’s go out and play!\nAnd get ourselves a cup of milk-tea!”]"
- 自定义的只能是一个字符,比如不能同时分隔掉‘ ’,!,’\n’
endwith\startswith
sentence='''What a nice day!'''
print "('!')=%r" % sentence.endswith('!')
print "('What')=%r" % sentence.startswith('What')
(’!’)=True
(‘What’)=True
6.2 列表
6.2.1 常用方法
- append(obj) – 在列表尾部添加新对象(原列表添加)
- extend(seq) – 在列表尾部一次性追加另一个序列中的多个值(原列表扩展)
- copy() – 创建一个浅拷贝(只复制了一级元素,其余的依然是引用)
- count(obj) – 计算obj出现的次数
- index(obj) – 找出第一个obj的匹配项的索引
- insert(index,obj) – 将obj插入到索引为index位置的元素前取而代之
- pop(index) – 移除索引为index的元素,并返回该元素的值,-1为最后一个
- remove(obj) – 移除第一个obj的匹配项
- reserve() – 元素反转
- sort(key=None,reserve=False) – 排序,可通过key指定排序依据;reserve决定是否逆序排列
- 复制 – l1=l2[:]
6.2.2 详细示例
append、extend
l1=[1,2,3,4,5]
l2=[6,7,8]
l1.append('a')
print "l1.append('a') % l1
print "\tl1=%r" % l1
l1_new=l1.extend(l2)
print "l1_new=(l2)\n\tl1=%r" % l1
print "\tl1_new=%r" % l1_new
(‘a’)
l1=[1, 2, 3, 4, 5, ‘a’]
l1_new=(l2)
l1=[1, 2, 3, 4, 5, ‘a’, 6, 7, 8]
l1_new=None
- 与字符串不同,扩展为对原列表的直接扩展,也就是说,会改变列表的值
copy\deepcopy
import copy
l1=[1,2,3,4,[5,6]]
l3=copy.copy(l1)
l1.append('a')
l1[4].append('b')
print "l3=(l1)\n\tl1=%r" % l3
l2=[1,2,3,4,[5,6]]
l4=copy.deepcopy(l2)
l2.append('a')
l2[4].append('b')
print "l4=(l1)\n\tl1=%r" % l4
l3=(l1)
l1=[1, 2, 3, 4, [5, 6, ‘b’]]
l4=(l1)
l1=[1, 2, 3, 4, [5, 6]]
【注意】
- copy模块需要导入
- copy的浅拷贝定义与c语言略有不同,因为其一级元素其实是深拷贝了的,但是其它子元素仍然是引用;如果想要全部深拷贝,则应该使用deepcopy。
index+count
l1=[1,2,3,4,5,1,1,2,3]
print "amount of 1 is:",l1.count(1)
print "first 1's index is:",l1.index(1)
amount of 1 is: 3
first 1’s index is: 0
insert
l1=[1,2,3,5,6]
l1.insert(3,4)
print l1
[1,2,3,4,5,6]
pop\remove
l1=[1,2,3,4,'a',5,6,'b',7]
l1.pop(4)
l1.remove('b')
print l1
[1, 2, 3, 4, 5, 6, 7]
[注意]
- pop不会改变原列表;remove会
- pop返回的值是被弹出的值,所以不会报错,所以要删除不要用pop!哟哦嗯remove!!
reverse
l=[1, 2, 3, 4, 5, 6, 7]
l.reverse()
print l
[7, 6, 5, 4, 3, 2, 1]
sort
def comp(x, y):#自己编写key函数
if len(x) > len(y):
return 1
elif len(x) < len(y):
return -1
else:
return 0
l=['abc','defg','c','bd']
l.sort()
print "():",l
l.sort(comp)
print "(comp):",l
(): [‘abc’, ‘bd’, ‘c’, ‘defg’]
(comp): [‘c’, ‘bd’, ‘abc’, ‘defg’]
6.3 元组
6.3.1 常用方法
- len(t)
- max(t) – 返回元组中元素的最大值
- min(t)
- tuple(seq) – 将序列转化为不可增修的元组
6.3.2 打包与解包
打包
单个元素
tup=1,2 -------> (1,2)
整个序列作为tuple元素
tup=l1,l2 -------> (l1, l2)
l1=[1,2]
l2=['a','b']
tup=l1,l2
print tup
-
结果:
([1,2],[‘a’,‘b’])
多个序例元素一一对应
zip
zip(l1,l2) -------> (tup1, tup2);tup1=[(l1[0],l2[0]),(l1[1],l2[1])]
l1=[1,2]
l2=['a','b']
l3=zip(l1,l2)
print l3
-
结果:
[(1, ‘a’), (2, ‘b’)]
6.4 注意
-
reversed(seq)与()有什么区别?
reversed(seq):不会改变seq本身,但可以返回一个逆序后的迭代器。
():会直接改变list本身,所以没有迭代器返回。
同理,sorted(seq)和()也是。
第7章 字典{dict:dict}
a:b – 将a与b相关联,可以通过a找到b,相当于是一个可以自定义索引的列表。
# -*- coding:utf-8 -*-
#建立一个字典
score_dict={'Annie':98,'Bonnie':83,'Jack':93,'Pennie':60+2}
#通过关键字获得内容
print ">>>Annie's score is:%r" % score_dict['Annie']
#添加元素
score_dict['Donald']=88
print score_dict
#删除元素
del score_dict['Pennie']
print score_dict
#打印所有成绩
for name,score in score_dict.items():
print ">>>%s's score is:%r" % (name,score)
#嵌套使用,首字母查询成绩
name_dict={'A':'Annie','B':'Bonnie','D':'Donald','J':'Jack','P':'Pennie'}
score=False
while not score:
print "Put firse character to check the score:[A\B\D\J\P]"
abbr=str(raw_input()).upper()
##使用get函数防止不包括关键字时出错
###用法一:
score=score_dict.get(name_dict[abbr]) #而不是score_dict[name_dict[abbr]]
if not score:
print "(方法一)>>>Sorry,%s is not in this class" % abbr
else:
print "(方法一)>>>%s's score is:%r" % (name_dict[abbr],score)
###用法二:
score=score_dict.get(name_dict[abbr],"Sorry,not exist".title())
print "(方法二)>>>%s's score is:%r" % (name_dict[abbr],score)
-
结果
Annie’s score is:98
{‘Pennie’: 62, ‘Donald’: 88, ‘Bonnie’: 83, ‘Annie’: 98, ‘Jack’: 93}
{‘Donald’: 88, ‘Bonnie’: 83, ‘Annie’: 98, ‘Jack’: 93}
Donald’s score is:88
Bonnie’s score is:83
Annie’s score is:98
Jack’s score is:93
Put firse character to check the score:[A\B\D\J\P]
p
(方法一)>>>Sorry,P is not in this class
(方法二)>>>Pennie’s score is:‘Sorry,Not Exist’
Put firse character to check the score:[A\B\D\J\P]
b
(方法一)>>>Bonnie’s score is:83
(方法二)>>>Bonnie’s score is:83
Put firse character to check the score:[A\B\D\J\P]
需要有序字典?
数据结构
第8章 集合{set}
集合中各元素间是无序的,相同元素在集合中唯一存在。即集合是无序组合,它没有索引和位置的概念,所以元素也不能含有列表、子集但可变集合中的元素是可以动态增加或删除的。
所以集合用来筛重很有效。
- set([iter]) – 将其它集合转化为集合,或者创建新集合;返回一个无重复元素且排序任意的可变集合。
- copy – 复制一个集合
- add – 为集合添加不存在的新元素。集合s已经存在元素x,也不会报错
- update – 将集合b并入集合a。
- discard – 移除集合s中的value元素。若value元素存在,则移除,不存在也不报错。
- remove – 移除集合s中的value元素。若value元素存在,则移除,不存在则报错(产生KeyError异常)。
- clear – 删除集合中的所有元素
- pop – 随机移除集合s中的一个元素并返回该元素。若集合为空则报错(产生KeyError异常)
- difference – 生成集合的差集。
- union – 生成集合的并集。即将集合a和集合b取并集,并将并集作为一个新的集合返回, 但是不改变原集合a和集合b
- intersection – 生成集合的交集。
- update – 将集合a和集合b取并集,并将结果保存在集合a中(即更新集合a),集合b不改变,但是没有返回值。
- symmetric_difference – 返回对称差集(反向交集),即返回两个集合中不重复的元素集合,即移除两个集合中都存在的元素。
- issubset() – 判断两个集合是否是子集关系(A⊆B)。即判断集合a中的所有元素是否都包含在集合b中,若都包含在集合b中则返回True,否则返回False
- isdisjoint() – 判断两个集合是否包含相同的元素,若没有相同元素则返回 True,否则返回 False。
# -*- coding:utf-8 -*-
num_list1=[1,2,3,4,3,'a']
num_list2=[3,4,3,14,7,44,'Hello']
set1=set(num_list1)
set2=set(num_list2)
print "1 set1:%r\tset2:%r" % (set1,set2)
set2_copy=set2.copy()
print "2 set2_copy:%r" % set2_copy
set2.add(5)
print "3 set2:%r" % set2
set2.discard(3)
#(3) #报错
print "4 set2:%r" % set2
set_difference=set1.difference(set2)
print "5>>>set_difference 1-2:%r" % set_difference
set3={4,1,2,2,3,23,13}
print "6 set3:%r:" % set3
set_union=set1.union(set2,set3)
print "7>>>set_union 1+2+3:%r" % set_union
#最后将筛重完成后的数据再储存在列表中
sum_list=list(set_union)
print "8>>>sum_list 1+2+3:%r" % sum_list
-
结果:
1 set1:set([‘a’, 1, 2, 3, 4]) set2:set([3, 4, 7, 44, 14, ‘Hello’])
2 set2_copy:set([3, 4, 7, 44, ‘Hello’, 14])
3 set2:set([3, 4, 5, 7, 44, 14, ‘Hello’])
4 set2:set([4, 5, 7, 44, 14, ‘Hello’])
5>>>set_difference 1-2:set([‘a’, 1, 2, 3])
6 set3:set([1, 2, 3, 4, 13, 23]):
7>>>set_union 1+2+3:set([‘a’, 1, 2, 3, 4, 5, 7, 44, 13, 14, 23, ‘Hello’])
8>>>sum_list 1+2+3:[‘a’, 1, 2, 3, 4, 5, 7, 44, 13, 14, 23, ‘Hello’]
第9章 模块、类、对象
- class – 告诉python创建一个新类型
- object – 对象:1.事物的基本类型 2.类的实例化
- instance – 实例
- self – 在一个类包含的函数中,用来访问实例或对象的变量
- attribute – 类所拥有的特性,通常是变量
- inheritance – 继承:一个类可以继承另一个类的特征
- composition – 包含:一个类包含其他类
- is-a – 表示一个东西继承自a
- has-a – 表示有其它东西a,或用于特征a
9.1 什么是模块?
一个需要import 的.py文件,像是一个通过filename.
调用的类.
1.创建mystuff模块
创建一个文件,内容如下:
#this from
def apple():
print "Apple!!!"
#variable
variable="Hi!~I'm a variable from !!!"
2.调用mystuff模块
再在同文件夹的另一个脚本中使用import调用该模块:
import mystuff
mystuff.apple()
print variable
-
结果
Apple!!!
Hi!~I’m a variable from !!!
与类的区别?
很显然,比方说你需要做一个【班级】的类,这个类里有一个变量叫做【人数】。你可以通过用类实例化多个对象(可以把类理解为类型,int、double其实也是类,int a,b,就是int被实例化了,a、b是他的对象),这些对象的【人数】变量根据实际情况设置为不同的值。但是模块呢?不好意思,它不存在对象,so,它只能有一个【班级】和【人数】变量。
9.2 类与对象
9.2.1 实例化
类的实例化方法与c++不太一样,是采用
对
象
=
C
l
a
s
s
(
)
对象=Class()
对象=Class()
的方式实例化出对象的。
9.2.2 几个例子
例子一:
1.创建mystuff模块,并在其中构建类Mystuff
#this from
class Mystuff:
def __init__(self):
self.variable="Hi!~I'm a variable from !!!" #与c++不同,不需要额外对成员变量进行定义,所以无论是否在成员函数内都一定要加self.说明该变量为成员变量
def apple(self):
print "Apple!!!"
2.使用mystuff模块,并使用类
# -*- coding:utf-8 -*-
import mystuff as ms
#实例化
stuff=ms.Mystuff()
print stuff.variable
stuff.apple()
-
结果:
Hi!~I’m a variable from !!!
Apple!!!
例子二:
soft kitty,walm kitty,little ball of fur
happy kitty,sleepy kitty,per per per
# -*- coding:utf-8 -*-
class Song(object): #Song是以类object为父级的,Song继承自object
def __init__(self,lyrics):
self.lyrics=lyrics
def sing_a_song(self):
for line in self.lyrics: #注意这里要用而不是lyrics,与c++不同,不需要额外定义成员变量意味着无论是否在成员函数内都一定要加self.说明该变量为成员变量
print line
with open("") as f:
lines=f.read()
lullaby =Song(lines.split("\n"))
lullaby =Song(["soft kitty,walm kitty,little ball of fur","happy kitty,sleepy kitty,per per per"])
lullaby.sing_a_song()
-
结果:
soft kitty,walm kitty,little ball of fur
happy kitty,sleepy kitty,per per per
9.2.3 与c++的区别
-
类的实例化方法与c++不太一样,是采用
对 象 = C l a s s ( ) 对象=Class() 对象=Class()
的方式实例化出对象的,而不是
C l a s s 对 象 Class 对象 Class对象 -
self:顾名思义,代表自己。每个成员函数都必须有一个self成员变量,有点像c++的*this,是一个在类包含的函数中访问实例或对象的变量。self.参数1为该类的参数1,与全局函数作区分。
Class Person: def func(): ...pass def func2(): self.func() ...pass Person person person.func()
-
不需要额外对成员变量进行定义,但是无论是否在成员函数内,都一定要加self.说明该变量为成员变量
9.3 类详解
9.3.1 定义
方法一
class Song(object): #Song是以类object为父级的,Song继承自object
...pass
- 子类实例化出来的对象,可以使用自身和父类的函数与变量。
方法二
__metaclass__= type #意味着下面的类是新式类
class Song:
...pass
9.3.2 初始化(与构造函数有些不同)
形式
d
e
f
_
_
i
n
i
t
_
_
(
s
e
l
f
,
∗
a
r
g
s
)
:
def\ \_\_init\_\_(self,*args):
def __init__(self,∗args):
- 用于给新对象赋初值
self是必须要有的成员变量,有点像c++的*this,是一个在类包含的函数中访问实例或对象的变量
设置参数默认值
class Person:
def __init__(self,name,language="Chinese")
9.3.3 类中函数
d e f f u n c _ n a m e ( s e l f , ∗ a r g s ) : def\ func\_name(self,*args): def func_name(self,∗args):
self
顾名思义,代表自己。每个成员函数都必须有一个self成员变量,有点像c++的*this,是一个在类包含的函数中访问实例或对象的变量。self.参数1为该类的参数1,与全局函数作区分。
Class Person:
def func():
...pass
def func2():
self.func()
...pass
Person person
person.func()
9.3.4 函数注释
使用三重引号
class Person:
"""This is a class"""
def __init__(self,name,language="Chinese"):
"""This is a function"""
...pass
- 这样最大的好处是可以用help()函数查看,#注释的内容则不可。
9.3.5 调用
对象调用类里变量/函数
对 象 . 变 量 / 函 数 名 对象.变量/函数名 对象.变量/函数名
类内调用自身/父类的变量/函数
s e l f . 变 量 / 函 数 名 self.变量/函数名 self.变量/函数名
# encoding=utf-8
class Animals:
def move(self):
print('moving\n')
class Mammals(Animals):
def breastfeed(self):
print('feeding young\n')
class Cats(Mammals):
def __init__(self, spots):
self.spots = spots
def catch_mouse(self):
print('catch mouse\n')
def left_foot_forward(self):
print('left_foot_forward\n')
def left_foot_backward(self):
print('left_foot_backward\n')
def dance(self):
self.left_foot_forward()
self.left_foot_backward()
kitty=Cats(10)
print('%r\n' % kitty.spots)
kitty.dance()
kitty.breastfeed()
kitty.move()
-
结果:
10
left_foot_forward
left_foot_backward
feeding young
moving
9.4 类属性和实例属性
c++类似