资源:
1.[小甲鱼]零基础入门学习Python
https://www.bilibili.com/video/av4050443/?from=search&seid=10660823011875778478
2.基于资料1中视频的官网,鱼C论坛有很多资料
http://bbs.fishc.com/forum-243-1.html
3.字符串内置方法
http://bbs.fishc.com/thread-38992-1-1.html
4.Python及bs4、lxml、numpy模块包的安装
http://blog.csdn.net/tiantiancsdn/article/details/51046490
5.Python 关键字
https://blog.csdn.net/liang19890820/article/details/68488392
6.python内置函数大全
https://www.cnblogs.com/pyyu/p/6702896.html
前言
1.版本
学习3.0,很多语法不兼容2.5
2.安装
下载3.6.4版本
软件:Sublime Text 3 , python自带IDLE
3.Bif 与 函数
Sublime Text3
安装:略
SublimeREPL插件: #可以直接输命令`
安装:#http://blog.chinaunix.net/uid-12014716-id-4269991.html
使用:#https://www.cnblogs.com/yshuangj/p/6404372.html
python IDLE快捷键
Alt+N Alt+P 可以查找以前输入的命令用于补全当前命令
库的使用: #参考资料4
1.使用pip安装,
安装pip
CMD到相应目录 : easy_install.exe pip
2.库的安装
from bs4 import BeautifulSoup
#pip3 install beautifulsoup4
from urllib import request
#python3自带
lxml解析器
#pip install lxml
学习:
//参考资料1视频
1.常用语法 与 基础
print("jiuya"+" java")
print("jiuya"*3)
print("jiuyan"*3) #换行
缩进是python的灵魂,需要正确的使用缩进
dir(__builtins__) #查看python有多少内置函数bif,里面不是所有都是bif,纯小写的是
help(input) #查看input作用
print('jiuya'! java') #字符串单引双引,需要转义
str = r'D:Javatomcat' #在字符串前加r 全部自动给字符转变成\
str='''大大大 #三重引号可以自动给字段加n
大大大a
dadavsxv'''
if a==0:
print('xxx')
else:
print('xxx')
3>2 and 1<2 #逻辑操作符 and
%d 只能输出整数,int类型
%f 输出浮点数
%s 输出string
type() #查看数据类型
isinstance(320,int) #判断数据类型,2参数:1.待确定参数,2.指定 , 返回True/False
2.引入模块
random :randint() #random模块中randint()函数会返回一个随机整数
import math #引入数学模块
3.python数据类型
str , float , bool , int
4.算数操作符
+ - * / % ** // # **冥运算 //float地板除法 去掉小数点后面的
>>> a=10
>>> b=9.999
>>> a//b
1.0
>>> a/b
1.000100010001
>>> b/a
0.9999
>>> b//a
0.0
>>>3**2 # 3*3
9
5.比较操作符
< <= > >= != ==
6.逻辑操作符
and or not
并 或 非
>>>not True
False
>>>not 0
True
>>>not 4
False
>>>3 <4 <5
True
7.分支循环 #其它和java差不多
if 条件:
print()
elif 条件:
print()
elif 条件:
print()
else:
print()
8.条件表达式(三元操作符)#2.5版本添加的
small= x if x<y else y
9.断言 assert
>>>assert 3>4 #当这个关键字后面条件为假,程序自动崩溃并抛出AssertionError的异常
10.while循环
11.for循环
member = ['fafa','啊a啊','搜索','嗯嗯']
for each in member:
print(each,len(member))
12.range()
语法:range([strat,] stop[,step=1])
#这个bif有三个参数,两个可选,step默认是1
>>> range(5)
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> for i in range(2,9):
print(i)
2
3
4
5
6
7
8
>>> for i in range(1,10,2):
print(i)
1
3
5
7
9
13.列表[]
普通列表,混合列表,空列表
member = ['fafa','啊a啊',3.14,[1,2,3]]
添加元素:
member.append(4) #追加
member.extend([5,6]) #扩展
member.insert(0,'法防')
member.remove('fafa')
del member[1] #del 是个语句不是方法
member.pop() #弹出;列表最后一个,弹出后列表没有该元素,可以有索引
member.pop(1) #弹出索引值为1的元素
列表分片:
member[1:3] #不包含3,不改变列表
member[:3]
14.列表上的常用操作符、
比较,逻辑,连接,重复,成员关系
(list1 > list2) and (list1 == list3)
>>>list1 = list1 + list3
>>>list1 * 3 #复制三遍,不改变列表
>>>list1 *= 3 #改变列表
>>>123 in list1 #返回bool,判断1层列表
>>>123 not in list1
#list1 = [123,['aa','bb'],44]
>>>'aa' in list1[1]
15.列表类型的内置函数
dir(list) #列举 list内置函数
list1.count(123) #计算123在list1中出现多少次
list1.index(123) #找到第一个出现的位置
list1.index(123,2,5) #指定范围
list1.reverse() #翻转
list1.sort() #排序 小到大
list1.sort(reverse=True) #大到小
16.元组:戴上枷锁的列表 tuple
#元组与list使用上非常相识,不可以被修改
创建和访问
>>> tuple1=(1,2,3,4,5)
>>> tuple1[1]
2
>>> tuple1[3:]
(4, 5)
#元组重点是, 不是()
>>> tuple1=1,2,3
>>> tuple1=1,
更新和删除
#以分片重组的方式
>>> tuple1=(1,2,3,4,5)
>>> tuple1=tuple1[:2]+(3.5,)+tuple1[2:]
(1,2,3,3.5,4,5)
元组相关操作符
+ 拼接操作符
* 重复操作符
in 成员操作符
not in 成员操作符
17.字符串内置方法
#http://bbs.fishc.com/thread-38992-1-1.html
切割
>>> str='12345'
>>> str[:3]
'123'
拼接
>>> str1=str[:3]+'插入'+str[3:]
>>> str
'12345'
>>> str1
'123插入45'
capitalize() #把字符串的第一个字符改为大写
>>> str2='abcdef'
>>> str2.capitalize()
'Abcdef'
casefold() #把整个字符串的所有字符改为小写
center(width) #将字符串居中,并使用空格填充至长度 width 的新字符串
count(sub[, start[, end]]) #返回 sub 在字符串里边出现的次数,start 和 end 参数表示范围,可选。
encode(encoding='utf-8', errors='strict') #以 encoding 指定的编码格式对字符串进行编码。
endswith(sub[, start[, end]]) #检查字符串是否以 sub 子字符串结束,如果是返回 True,否则返回 False。start 和 end 参数表示范围,可选。
expandtabs([tabsize=8]) #把字符串中的 tab 符号(t)转换为空格,如不指定参数,默认的空格数是 tabsize=8。
find(sub[, start[, end]]) #检测 sub 是否包含在字符串中,如果有则返回索引值,否则返回 -1,start 和 end 参数表示范围,可选。
index(sub[,start[,end]]) #与find差不多,如果sub不在字符串中会产生一个异常
isalnum() #字符串至少有一个字符,字母数字都可以,有True 无false
isalpha() #至少一个,只能是字符串 true false
isdigit() #只包含数字
islower() #只能是小写
replace(old, new[, count]) #把字符串中的 old 子字符串替换成 new 子字符串,如果 count 指定,则替换不超过 count 次。
strip([chars]) #移除字符串头尾指定的字符(默认为空格)
....
18.字符串格式化
#Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
>>>"{0} love {1}.{2}".format('I','rekoo','com')
格式化符号:
#http://www.runoob.com/python3/python3-string.html
%c 格式化字符及其ASCII码
%s 格式化字符串
%d 格式化整数
%u 格式化无符号整型
%o 格式化无符号八进制数
%x 格式化无符号十六进制数
%X 格式化无符号十六进制数(大写)
%f 格式化浮点数字,可指定小数点后的精度
%e 用科学计数法格式化浮点数
%E 作用同%e,用科学计数法格式化浮点数
%g %f和%e的简写
%G %f 和 %E 的简写
%p 用十六进制数格式化变量的地址
>>> '%c' %97
'a'
>>> '%c%c%c' %(97,98,99)
'abc'
格式化操作符辅助指令:
#http://www.runoob.com/python3/python3-string.html
m.n. #一般配合%f使用, m是总宽度,n是小数点后位数
转义符号:
....
19.序列
#列表,元组,字符串
Bif: #内置方法
#help(list)
list() #可迭代对象转list
tuple()#可迭代对象转tuple
len(sub)#返回长度
max()#返回最大
sum()
sorted()
zip() # 打包为元组的列表
reversed() #反转,是一个对象,需要list()
20.函数
def MyFunction(name,word):
print('ssss')
属性:
MyFunction.__doc__
参数:
关键字参数: 可以用在function 上也可以用在, 调用时
内部/内嵌 函数:
def fun1():
print('fun1调用')
def fun2():
print('fun2调用')
fun2()
21.闭包
def funX(x):
def funY(y):
return x * y
return funY
使用闭包:
>>>i=funX(8)
>>>i(5)
40
>>>funX(8)(5)
>>>40
22.lambda 表达式
#创建函数,省下定义函数过程, 把函数变成一句话函数
>>>t=lambda x:2*x
>>>t(5)
10
23.递归
24.字典 #dict 映射类型, K/V
字典是python唯一的映射类型 #不用索引时, 就可以用字典,
# http://www.runoob.com/python/python-dictionary.html
s={'a':'A','b':'B','c':'C'}
25.集合 #set
s={'a','b','c'}
s=set(['元组/列表/str'])
1.具有唯一性,
2.无序
3.不支持索引
方法:
v in set
set.add(v)
.remove(v)
不可变集合:
frozen:冰冻的
frozenset([1,2,3,4])
26.输入 输出 处理
open() 函数用于打开一个文件,创建一个 file 对象
# http://www.runoob.com/python/python-func-open.html
open(name[, mode[, buffering]])
打开模式:
r只读(默认), w写 覆, a写 追加
方法:
.close()
.read(size=-1)
.readline() #写入模式打开,文件存在,末尾追加
.write(str) #将str写入文件
00.Python关键字
global 定义全局变量 #可以把函数中局部变量变成全局函数
nonlocal 与global使用是一样的 #细节自己百度吧
00.内置函数:
filter(function, iterable) #过滤器
#>>>list(filter(lambda x:x%2,range(10)))
#[1,3,5,7,9]
map(function, iterable, ...) #遍历每个元素,执行function操作
#>>> list(map(lambda x:x*2,range(10))) 把range生成的值, 放入前面函数得到加工后的值
#[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
命令/关键字:
scrapy:
scrapy startproject XXXXX //创建项目
yield
python:
问题:
1.list的分片拷贝与直接赋值
list1=list2[:] #创建一个空间
lisr1=list2 #使用同一个地址,只是多了一个指向
2.list拼接
list1=list1+list2
list1=list1.extend(list2)
#结果是一样的
3.sort 与 sorted 区别:
#http://www.runoob.com/python3/python3-func-sorted.html
sort是list的,但是sorted 可以对所有可迭代的对象进行排序操作。
list1.sort()
sorted(list1)
4.在linux下编辑文件
缩进使用4个空格,linux类默认是空格,如果用Tab那就必须全换成Tab
5.软链的使用 20180329设置python3软链时get
ln -s /usr/local/python3/bin/python3 /usr/bin/python
设置软连后,会创建一个文件, 如果错误了,需要删除在设置
6.Python中的None
# https://blog.csdn.net/baicaiye/article/details/72922197
7.在闭包中return funX 与return funX() 是有区别的
funX是返回函数, funX()是执行函数
字符串
python默认ascii码。使用单引号和双引号效果一样。
跟C语言类似,可以使用进行转义:n换行,t制表符,r回车符, 空值(Null)
如果长字符串需要跨越多行,有如下三种方法:
- 使用'''xxxxxxxx'''代替普通引号
- 使用三个"""xxxxxxxx"""
- 在每行最后加上将换行符转义。
原始字符串:如果在字符串前加上r,即输出引号中原始字符串 print r'let's
go!',不能在原始字符串尾部输入,除非对其进行转义
字符串的索引:a[0],字符串偏移量从0开始,最后一位从-1开始。字符串的值不可原地改变。
+为字符串的拼接,*为字符串的重复
查看字符串具有的方法:help(str),dir(str)
count(self, sub, start=None,
end=None):用于统计字符串里某个字符出现的次数,可选参数为在字符串搜索的开始与结束位置。sub
–> 搜索的子字符串,start –>
字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。end –>
字符串中结束搜索的位置。字符中第一个字符的索引为
0。默认为字符串的最后一个位置。
decode(self, encoding=None,
errors=None):解码,对于len在处理汉字的时候因为返回的是字节数目导致结果不符,可以使用decode转码,或者len(u"哈哈")
encode(self, encoding=None, errors=None):编码,针对unicode
find(self, sub, start=None,
end=None):检测字符串中是否包含子字符串str,如果指定beg(开始)和end(结束)范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
isalnum(self):法检测字符串是否由字母和数字组成,如果string至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False
isalpha(self):
split: S.split([sep [,maxsplit]]) -> list of
strings返回一个list
join:
replace:
translate:
示例:打印出字符串中的字符及其位置
a = 'shsh'
for i in range(len(a)):
print '(%d)' % i,a[i]
也可以使用enumerate()函数:
a = 'shsh'
for i,ch in enumerate(a):
print '(%d)' % i,ch
示例:取出字符串中的数字
a = "aAsmr3idd4bgs7Dlsf9eAF"
print ''.join([x for x in a if x.isdigit()])
示例:字符串的拼接
1.c = a + b
2.c = "{a}{b}" .format(a=a,b=b)
3.c = "%s%s" % (a,b)
4.c="".join([a,b])
is
classmethod修饰符,声明类方法,类方法的第一个参数是cls,和实例方法的self意义相同。如果有继承关系,子类方法调用类方法时,传递的类变量cls时子类,而非父类。
问题:1.list的分片拷贝与直接赋值list1=list2[:]#创建一个空间lisr1=list2 #使用同一个地址,只是多了一个指向2.list拼接list1=list1+list2list1=list1.extend(list2)#结果是一样的3.sort 与 sorted 区别:# sort是list的,但是sorted 可以对所有可迭代的对象进行排序操作。list1.sort()sorted(list1)4.在linux下编辑文件 缩进使用4个空格,linux类默认是空格,如果用Tab那就必须全换成Tab5.软链的使用20180329设置python3软链时getln -s /usr/local/python3/bin/python3 /usr/bin/python设置软连后,会创建一个文件, 如果错误了,需要删除在设置6.Python中的None# funX 与return funX() 是有区别的funX是返回函数, funX()是执行函数
dict函数
items=[('name','grb'),('age',42)]
d=dict(items) #或者通过关键字创建 d=dict(name='grb',age=42)
print d
- In python , origin string is userful , maybe the follow result is not you except
tuple()将列表转换为元组
二进制符号
位移 >> <<
x << y x >> y #左移(补0)和右移(切尾)是基于二进制的一种算法 >>、 <<,使用bin函数查看二进制
x << y == x * ( 2 ** y )
可用于计算硬盘容量,比如 1024 >> 10按位与 &
二进制靠右对齐,不足补0,比较位置都是1则返回1,其他位返回0
可用于奇偶数判断,数值与1进行&运算,返回0则为偶数,返回1则为奇数:5 & 1 == 1按位或 |
二进制靠右对齐,不足补0,比较位置只要有1,则返回1按位异或 ^
比较位相异返回1,相同返回0按位取反 ~
help(……) such as help(input),int()
min()求最小值
资源:1.[小甲鱼]零基础入门学习Python
关键字
Text 3 , python自带IDLE3.Bif 与 函数Sublime
Text3 安装:略SublimeREPL插件:
#可以直接输命令`安装:#
python IDLE快捷键Alt+N Alt+P 可以查找以前输入的命令用于补全当前命令
库的使用: #参考资料41.使用pip安装,安装pipCMD到相应目录 :
easy_install.exe pip2.库的安装from bs4 import BeautifulSoup#pip3
install beautifulsoup4from urllib import request
#python3自带lxml解析器#pip install lxml学习://参考资料1视频1.常用语法
与 基础print("jiuya"+" java")print("jiuya"*3)print("jiuyan"*3)
#换行缩进是python的灵魂,需要正确的使用缩进dir(__builtins__)
#查看python有多少内置函数bif,里面不是所有都是bif,纯小写的是help(input)
#查看input作用print('jiuya'! java') #字符串单引双引,需要转义str =
r'D:Javatomcat' #在字符串前加r
全部自动给字符转变成\str='''大大大#三重引号可以自动给字段加n大大大adadavsxv'''if
a==0:print('xxx')else:print('xxx')3>2 and 1<2 #逻辑操作符 and%d
只能输出整数,int类型%f 输出浮点数%s 输出stringtype()
#查看数据类型isinstance(320,int)
#判断数据类型,2参数:1.待确定参数,2.指定 ,
返回True/False 2.引入模块random :randint()
#random模块中randint()函数会返回一个随机整数import math
#引入数学模块3.python数据类型str , float , bool , int
4.算数操作符+ - * / % ** // #**冥运算 //float地板除法
去掉小数点后面的>>> a=10>>> b=9.999>>>
a//b1.0>>> a/b1.000100010001>>> b/a0.9999>>>
b//a0.0>>>3**2 # 3*395.比较操作符< <= > >= !=
==6.逻辑操作符and or not 并 或 非>>>not
True False>>>not 0True>>>not 4False>>>3 <4
<5True7.分支循环 #其它和java差不多if 条件:print()elif
条件:print()elif
条件:print()else:print()8.条件表达式(三元操作符)#2.5版本添加的small=
x if x<y else y9.断言 assert >>>assert 3>4
#当这个关键字后面条件为假,程序自动崩溃并抛出AssertionError的异常10.while循环11.for循环member
= ['fafa','啊a啊','搜索','嗯嗯']for each in
member:print(each,len(member))12.range()语法:range([strat,]
stop[,step=1])#这个bif有三个参数,两个可选,step默认是1>>>
range(5)range(0, 5)>>> list(range(5))[0, 1, 2, 3,
4]>>> for i in range(2,9):print(i)2345678>>> for i in
range(1,10,2):print(i)1357913.列表[]普通列表,混合列表,空列表member =
['fafa','啊a啊',3.14,[1,2,3]]添加元素:member.append(4)
#追加member.extend([5,6])
#扩展member.insert(0,'法防')member.remove('fafa')del member[1]#del
是个语句不是方法member.pop()
#弹出;列表最后一个,弹出后列表没有该元素,可以有索引member.pop(1)
#弹出索引值为1的元素列表分片:member[1:3]#不包含3,不改变列表member[:3]14.列表上的常用操作符、比较,逻辑,连接,重复,成员关系
(list1 > list2) and (list1 == list3)>>>list1 = list1 +
list3>>>list1 * 3 #复制三遍,不改变列表>>>list1 *=
3 #改变列表>>>123 in list1
#返回bool,判断1层列表>>>123 not in list1#list1 =
[123,['aa','bb'],44]>>>'aa' in
list1[1] 15.列表类型的内置函数dir(list) #列举
list内置函数list1.count(123)
#计算123在list1中出现多少次list1.index(123)
#找到第一个出现的位置list1.index(123,2,5) #指定范围list1.reverse()
#翻转list1.sort() #排序 小到大list1.sort(reverse=True)
#大到小16.元组:戴上枷锁的列表
tuple#元组与list使用上非常相识,不可以被修改创建和访问>>>
tuple1=(1,2,3,4,5) >>> tuple1[1] 2>>>
tuple1[3:] (4, 5)#元组重点是, 不是()>>>
tuple1=1,2,3>>>
tuple1=1,更新和删除#以分片重组的方式>>>
tuple1=(1,2,3,4,5) >>>
tuple1=tuple1[:2]+(3.5,)+tuple1[2:](1,2,3,3.5,4,5) 元组相关操作符+
拼接操作符* 重复操作符in 成员操作符not
in成员操作符17.字符串内置方法#;
str='12345'>>> str[:3]'123'拼接>>>
str1=str[:3]+'插入'+str[3:]>>> str'12345'>>>
str1'123插入45'capitalize() #把字符串的第一个字符改为大写>>>
str2='abcdef'>>> str2.capitalize()'Abcdef'casefold()
#把整个字符串的所有字符改为小写center(width)
#将字符串居中,并使用空格填充至长度 width 的新字符串count(sub[,
start[, end]]) #返回 sub 在字符串里边出现的次数,start 和 end
参数表示范围,可选。encode(encoding='utf-8', errors='strict') #以
encoding 指定的编码格式对字符串进行编码。endswith(sub[, start[,
end]]) #检查字符串是否以 sub 子字符串结束,如果是返回 True,否则返回
False。start 和 end 参数表示范围,可选。expandtabs([tabsize=8])
#把字符串中的 tab 符号(t)转换为空格,如不指定参数,默认的空格数是
tabsize=8。find(sub[, start[, end]]) #检测 sub
是否包含在字符串中,如果有则返回索引值,否则返回 -1,start 和 end
参数表示范围,可选。index(sub[,start[,end]])
#与find差不多,如果sub不在字符串中会产生一个异常isalnum()
#字符串至少有一个字符,字母数字都可以,有True 无falseisalpha()
#至少一个,只能是字符串 true falseisdigit() #只包含数字islower()
#只能是小写replace(old, new[, count]) #把字符串中的 old
子字符串替换成 new 子字符串,如果 count 指定,则替换不超过 count
次。strip([chars])
#移除字符串头尾指定的字符(默认为空格)....18.字符串格式化#Python2.6
开始,新增了一种格式化字符串的函数
str.format(),它增强了字符串格式化的功能。>>>"{0} love
{1}.{2}".format('I','rekoo','com')格式化符号:#
%c 格式化字符及其ASCII码 %s 格式化字符串 %d 格式化整数 %u
格式化无符号整型 %o 格式化无符号八进制数 %x 格式化无符号十六进制数 %X
格式化无符号十六进制数(大写) %f 格式化浮点数字,可指定小数点后的精度
%e 用科学计数法格式化浮点数 %E 作用同%e,用科学计数法格式化浮点数 %g
%f和%e的简写 %G %f 和 %E 的简写 %p
用十六进制数格式化变量的地址>>> '%c' %97 'a'>>>
'%c%c%c'
%(97,98,99)'abc'格式化操作符辅助指令:#.
#一般配合%f使用,
m是总宽度,n是小数点后位数转义符号:....19.序列#列表,元组,字符串Bif:
#内置方法#help(list)list()
#可迭代对象转listtuple()#可迭代对象转tuplelen(sub)#返回长度max()#返回最大sum()sorted()zip()
# 打包为元组的列表reversed() #反转,是一个对象,需要list()20.函数def
MyFunction(name,word):print('ssss')属性:MyFunction.__doc__参数:关键字参数:
可以用在function 上也可以用在, 调用时内部/内嵌 函数:def
fun1():print('fun1调用')def fun2():print('fun2调用')fun2()21.闭包def
funX(x):def funY(y):return x * yreturn
funY使用闭包:>>>i=funX(8)>>>i(5)40>>>funX(8)(5)>>>4022.lambda
表达式#创建函数,省下定义函数过程,
把函数变成一句话函数>>>t=lambda
x:2*x>>>t(5)1023.递归24.字典 #dict 映射类型,
K/V 字典是python唯一的映射类型 #不用索引时, 就可以用字典,#
, 2.无序3.不支持索引方法:v
in setset.add(v)
.remove(v)不可变集合:frozen:冰冻的frozenset([1,2,3,4])26.输入 输出
处理open() 函数用于打开一个文件,创建一个 file 对象#
, mode[,
buffering]])打开模式:r只读(默认), w写 覆, a写
追加 方法:.close().read(size=-1).readline()
#写入模式打开,文件存在,末尾追加.write(str) #将str写入文件
00.Python关键字global定义全局变量
#可以把函数中局部变量变成全局函数nonlocal 与global使用是一样的
#细节自己百度吧00.内置函数:filter(function, iterable)
#过滤器#>>>list(filter(lambda
x:x%2,range(10))) #[1,3,5,7,9]map(function, iterable, ...)
#遍历每个元素,执行function操作#>>> list(map(lambda
x:x*2,range(10))) 把range生成的值, 放入前面函数得到加工后的值#[0, 2,
4, 6, 8, 10, 12, 14, 16, 18]命令/关键字:scrapy:scrapy startproject
XXXXX //创建项目yieldpython:
list 列表
方括号中,逗号分隔,索引下标从0开始。类型可变,元素的类型可以不同,可以包含任意类型的python对象。支持嵌套,list里也可以包含一个list。可原地修改内容。
创建一个空列表:
names = []
names = list()
有序集合
classmate = ['Micherl','Bob','Marry']
len(classmate),max(classmate),min(classmate)
classmate[0] classmate[-1] #取值
classmate[1]='Kack'
#赋值,不能赋值超过列表长度,可以先进行初始化,再进行赋值
del classmate[1] #删除元素,后面元素前移
'Marry' in classmate #in or not in判断元素是否在列表中
classmate.index('Micherl')
使用+运算符可以连接列表
sorted(iterable, key=None, reverse=False),key用来进行比较的元素,指定可迭代对象的一个元素来进行排序,reverse排序规则,True为降序,False为升序。和list.sort()的区别:sorted会修改原始的list,list.sort()返回为None;另外list.sort()只为list定义,sorted函数可以接受任何iterable。eg:print(sorted({1:'A', 2:"B", 3:"C"}))
str和repr
str函数用于将值转化为适用于人阅读的形式,相当于to string
repr函数转化为供解释器读取的形式,创建一个合法的字符串表示值,repr(x)等同x
print '1+2='+1+2
//this is second day to study python(2016/8/1)
open()用于打开一个文件,创建一个file对象
列表推导式
[expr for iter_var in iterable]
:首先迭代iterable里所有的内容,每一次迭代都把iterable中的内容放到iter_var中,再在表达式中应用该iter_var的内容,最后用表达式计算值生成一个列表。
[x+1 for x in range(1:11)]
可以这样理解这个推导式
new_list=[]
for x in range(1:11)
new_list.append(x+1)
print new_list
[expr for iter_var in iterable if cond_expr]
:加入了判断语句,只有满足cond_expr条件的才把iterable丢到iter_var,最后用表达式生成列表
[x+1 for x in range(1:11) if x % 2 == 1]
生成字符串:['the %s' % d for d in xrange(10)]
生成元组:[(x,y) for x in range(2) for y in range(2)]
生成字典:dict([(x,y) for x in range(3) for y in range(3)])
g = {i:j.upper() for i,j in zip(range(1,6),'abcde')}
//this is my first day to study python, in order to review, every day i will make notes (2016/7/31)
chr() 将0~255范围内的整数转换为对应的ascii字符
列表的方法
classmate.append('Adam') #追加,返回值并不是新的list,而是none
classmate.count('Bob') #某元素出现次数
classmate1.extend(classmate2) #将b扩展到a后面,a的列表刷新了
classmate.index('Bob') #值追索引
classmate.insert(1,'Jack') #1至后面的元素集体后移,插队
classmate.pop(1) #退出最后一个元素,与append类似栈,后进先出
classmate.remove('Bob') #删除第一个匹配元素
classmate.reverse #元素反向
sort方法:
x=[1,3,2,6,4]
y=x[:]
#不能简单的y=x.sort()因为sort方法无返回值,也可以使用sorted(x),可以返回排序后的列表
y.sort()
print x
print y
- In python , type conversion is userful , the follow is base conversion
isinstance() 用于判断一个对象是否是某一类型,类似type,但type不会认为子类是父类类型,isinstance会认为子类是父类类型
dict 字典
花括号,逗号分隔,key和value使用冒号分隔,key唯一,value不一定唯一.无序,不能通过偏移取值。可变类型,可嵌套。
创建一个空字典
d = {}
d = dict()
组成字典的键必须是不可变的数据类型,比如数字、字符串、元组等,列表等可变类型不可作为键
d = {'Michael': 95,'Bob': 75, 'Tracy': 85} #创建字典
d['Michael']
d['Adam'] = 67 #增加数据或者更新数据
del d['Michael'] #删除字典元素
'Thomas' in d #判断是否存在KEY d.has_key('Thomas')
such as :
hex() 将十进制整数转换为16进制
列表深复制和浅复制
浅复制:
a=[1,2,[3,4]]
b=a
b is a #b和a指向同一个对象
del b
print a #删除b后,既删除b的指向,a无变化
print b
b=list(a) #创建一个a的浅复制
b is a #False
b.append(100) #给b追加一个元素
print a #a无变化
print b #b增加了一个元素
b[2][0]=-100
print a
print b #注意a的变化
c=a
del c[:]
print a
print c
深复制将创建一个新的对象,并且递归复制它所包含的所有对象
import copy
a = [1,2,[3,4]]
b = copy.deepcopy(a)
b[2][0] = -100
print a
print b
temp and Temp is not same variable
abs() 获取绝对值
zip函数
zip(s,t)函数将列表s和列表t组成一个元组列表(s[0],t[0])、(s[1].t[1])等,如果s和t长度不等,则以短的长度为止。
zip函数在python2中会完全创建一个元组列表,函数itertools.izip一次只生成一个元组,性能较好
oct()将一个整数转换成8进制字符串
tuple 元组
一旦初始化就不能修改,括号,逗号分隔。不能原地修改,不能排序。
classmates = ('Michael', 'Bob', 'Tracy')
tuple的陷阱:当你定义一个tuple时,在定义的时候,tuple的元素就必须被确定下来,
只有1个元素的tuple定义时必须加一个逗号,防止歧义(以下两种方式都可以)
t = (1,)
t = 1, #即使没有圆括号,python也可以识别出元组
以下示例看起来元组被改变了,查看id发现元组对象已经被改变了
a = (1,2)
b = list(a)
type(b)
b[0] = 5
a = tuple(b)
print a
type(a)
id()用于获取对象的内存地址
set 集合
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。没有顺序的概念,所以不能切片和索引操作。
t = set("hello") #创建一个唯一字符的集合
t
s = set([1, 2, 3])
s
s.add(4) #添加一项
s.update([7,8,9,10]) #添加多项
s.remove(4) #删除一项
成员操作关系 in 、not in
交集( & )、并集( | )、差集( - )、对称差集(^)
a = t | s
b = t & s
c = t - s
d = t ^ s #t和s中,但不同是在t和s中
判断集合是否相等与顺序无关 print set('abc') == set('bac')
列表的去重:
a = [1,2,3,3,4,4,5]
b=list(set(a))
frozenset()不可变集合
- In python , if a string , you want to change row ,you can user ''' ,if you not user ''' and change row ,it will appear an error
staticmethod修饰符,声明静态方法,类不需要实例化就可以调用该方法。
字典的方法
d.clear() #清空
d.get('Thomas')
d.get('Thomas', -1) #如果不存在Thomas则返回-1
d.pop('Bob') #删除一个Key,对应的value也删除
d.update({'Michael': 99})
d.keys() #返回键的列表 等同于list(d)
d.values() #返回值的列表
d.items() #生成一个字典的容器 [()]
int or string -> float
such as:
a = '26' b = float(b) print(b) -> 26.0
a = 'qq' b = float(b) error
a = 26 b = float(b) print(b) -> 26.0
pow(),c风格的几次方,math.pow(x, y)
xrange and range
range:直接生成一个列表对象
xrange:生成一个xrange对象。当需要生成比较大的数据,内存比较紧张,xrange比较省内存。xrange一般用在循环里面,比如只需要操作部分数据,而不是返回全部元素来完成操作的情况
for m in range(1000): #一次性生成1000个数字
if m == 10:
print "ss"
break
for m in xrange(1000): #只生成10个数字
if m == 10:
print "ss"
break
在python3种xrange()函数已经更名为range(),并且已经删除了老式range()函数的功能。
- In python , there are many bulit-in funcation. you can use follow to find out hou many built-in funcation:
hasattr(object, attr)用于判断一个对象是否有某一属性
数据类型
数据类型由三部分组成身份(id)、类型(type)、值。
澳门新濠3559,看对象有没有改变使用id(object)查看对象的内存地址是否改变。
def compare(a,b):
if a is b: #a和b是同一个对象
statements
if a == b: #a和b具有相同的值
statements
if type(a) =type(b): #a和b具有相同的类型
statements
python能直接处理的数据类型有以下几种(type)
数值number:整数int,长整型long,浮点数float
#python3中long不存在,int可以存储64位整数
布尔值bool:True、False
#注意大小写,在与数值运算时,True的值为1,False的值为0
空值:None
字符串:str
线性容器:list,tuple #支持迭代,字符串也是一种线性容器
Hash容器:dict,set
如果对象的值是可以修改的,则称为可变对象(mutable),否则成为不可变对象(immutable)。
可以进行对象类型和值的对比。其他比较操作符也支持>、<、>=、<=、!=、==,逻辑操作符and、or、not
me'''
float()将整数和字符串转换成浮点数
数值
查看int对象所具有的方法:help(int),dir(int),int.doc
bit_length(Number of bits necessary to represent self in binary.返回表示该数字的时占用的最少位数)
a = 1
print a.bit_length()
print('Let's go!')
filter()用于过滤序列,函数返回filter对象
字符串格式化format
在Python中,采用的格式化方式和C语言是一致的,用%实现;
有几个%?,后面就跟几个变量,顺序需要一致(只有一个变量的时候,括号可以省略);如果不太确认用什么,可以直接使用%s将任何数据类型转换为字符串;
字符串里含%可用%%进行转义,来表示一个%;
可以在"%"和字母之间插进数字表示最大场宽。 例如: %3d 表示输出3位整型数,
不够3位右对齐。 %9.2f 表示输出场宽为9的浮点数, 其中小数位为2, 整数位为6,
小数点占一位, 不够9位右对齐。
%d 整数 :print "1+1 = %d " % int(1+1)
%f 浮点数
%s 字符串 : print "my name is %s lilei" % "hanmeimei's"
%x 十六进制整数
'%s is a %s' % ('he','boy')
字典形式的字符串的格式化更加灵活,注意花括号的位置
'%(who)s is a %(gender)s' %{'who':'he','gender':'boy'}
"this is {whose} {fruit}" .format (fruit = "apple" , whose = "my")
such as:
zip()将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回zip对象。如果各个迭代器的元素个数不一致,则zip对象包含的列表长度与最短的对象相同,利用*号操作符,可以将元组解压为zip对象。
分片
classmate[1:2]
第一个索引包含在分片内,第二个索引不包含在分片内,一般第三个参数默认为1,步长如果为负数,则从右到左提取元素。
分片赋值 classmate[2:]='a' 相当于替换元素
分片删除 del classmate[2:]
列表可以进行相加 print
[1,2,3]+[3,4],相同类型才能进行相加,如列表和字符串不能进行加减
乘法:序列乘以数值,则序列会被重复数值次数,
空值 None 如果要初始化一个长度为10的空序列 seq=[None]*10
检查一个值是否在序列中 'Micherl' in classmate 返回布尔值
列表、元组和字典字面量可以在不使用续行符()的情况下分步多行,另外最后一项允许跟一个逗号
a = [1,
3,4,
"hello",
]
返回可迭代对象,start默认为0,step默认为1。
such as:
format()格式化函数
str = 'c:nowdata'
int()将一个字符串或数字传换成整数,int(x, base=10)
- In python , when you define variable ,uppercase and lowercase is different.
数学函数
if you want get BIF detail, you can use follow code:
面向对象相关函数
you can solve this problem by str = r'c:nowdata' ,this code is equal to str = 'c:\now\data'
bin()返回一个整型int或long int的二进制表示
str = '''this
delattr(object, attr) 用于删除属性
this
list()将元组转换为列表
owdata
sum(),对序列进行求和
print(str)
range(start, stop[,step])
def is_odd(n):
return n % 2 == 1
aList = filter(is_odd, [1, 2, 3, 4, 5, 6, 7])
print(list(aList))
print(str)
进制转换
a = 'qq' b = int(a) error
python有一些常用的内置函数:
- In python , we can see 'e' as 10
slice(stop),或slice(start, stop[, step])实现切片对象。print([1, 2, 3, 4, 5, 6, 7][slice(3)])
hash()获取一个对象(字符串或数值)的哈希值
迭代相关函数
1.5e4 == 15000.0
列表、元组、字典相关函数
when you print(str), the result will be c:nowdata
其它
is
max()求最大值
import random
a = [1, 2, 3]
b = ['one', 'two', 'three']
zipped = zip(a, b)
zipList = []
for it in zipped:
print(it)
zipList.append(it)
print(zipList)
for it in zip(*zipList):
print(it)
int or float -> str
such as:
a = 26 b = str(a) print(b) -> '26'
a = 3.14 b = str(a) print(b) -> '3.14'
a = 5e19 b = str(a) print(b) -> '5e+19'
sometimes, we need to be care to str,
such as:
str = 'I like apple'
print(str) -> 'I like apple'
but if it is c = str(5e19) ,it will appear an error ,because str is BIF ,we define str again , it will have new means, so it will have error
- In python ,we can get the type of variable
such as:
a = 'qq'
type(a) -> <class 'str' at 0x----->
a = 3.0
type(a) -> <class 'float' at 0x--->
a = True
type(a) -> <class 'bool' at 0x--->
we recommand follow:
a = 'roy'
isinstance(a, str) -> True
isinstance(a, int) -> False
but sometimes you need to know it maybe account an error:
TypeError: isinstance() arg 2 must be a type or tuple of types
the reason is may you define str before, In python ,you can change built-in funcation, so when you define variable ,you should try to avoid user special chararctes. such as try not to use BIF.
- In python , arithmetic operators has
- - * / ** // %
a += 4 <==> a = a + 4
a = 2
b = 3
a / b -> 0.6666666666666666
a // b -> 0
b // a -> 1
a % b -> 2
b % a -> 1
a * b -> 8
b ** a -> 9
- In python , logical operators includes and , or , not
such as:
not Ture
False
- In python , if and else how to use:
score = int(input('please input score:'))
if 90<= score <= 100:
print('A')
elif 80<= score < 90:
print('B')
elif 60<= score < 80:
print('C')
else:
print('D')
14. trinocular operator
small = x if x < y else y
->
x, y = 4, 5
if x < y:
small = x
else:
small = y
- assert ,when condication is false , it will have assertionerror
such as:
assert 3 > 4
>>> assert 3>4
Traceback (most recent call
last):
File "<pyshell#1>", line 1,
in <module>
assert 3>4
AssertionError
//third day study python (2016/8/2)
- In python , how to achieve 'for' loop:
for target in expression:
loop body
such as:
string = 'roy'
for i in string:
print(i)
->
r
o
y
students = ['wyg' , 'roy]
for each in students:
print(each,len(each))
- In python , range() is often combined with for loop , what's range()
range([start,] stop [, step = 1]) // three para
[] represent select
step = 1 represent by default step is 1
so it is from start to stop number list
range(3) -> range(0,3)
list(range(4)) -> [0, 1, 2, 3]
for i in range(2,5):
print(i)
result is :2 3 4
for i in range(1,10,4):
print(i)
result is :1 5 9
- In python , there are also have break and continue
continue skip current loop
break end loop
19. In python , there are no array ,but have list and more power
such as:
mixType = [1, 'roy', 3.14, [5, 6]]
we can also create an empty list:
empty = []
how to add content to list:
empty.appen(3) -> 3
or
empty.extend([3, 6, 9]) -> 3 3 6 9
or
empty.insert(0, 'aaa') -> 3 'aaa 3 6 9
how to get value according to subscript:
empty[0] -> 3
how to delete value
empty.remove(9) -> 3 'aaa' 3 6
or
del temp[1] -> 3 3 6
if you want to delete from memary , you can use del temp
or
temp.pop() -> [3, 3]
you also can pop value according to subscript
such as :temp.pop(1)
slice is useful ,you can achieve amazing thing:
such as :
aaa = [1, 2, 3, 4, 5, 6]
aaa[1:4] -> [2,3,4]
aaa[:3] -> [1,2,3]
aaa[1:] -> [2,3,4,5,6]
aaa[:] = [1,2,3,4,5,6]
aaa -> [1,2,3,4,5,6]
- In python , how to compare to list
list1 = [123,456]
list2 = [234,345]
list1 > list2
-> False
list1 + list2
-> [123,456,234,345]
list1 * 2
-> [123,456,123,456]
456 in list1
-> True
456 not in list1
-> Falsse
list3 = [1,2,[3,4]]
3 in list3
-> False
3 in list3[2]
-> True
list3[2][1]
-> 4
- In python , how many method of list
we can use dir(list) to find out it
now i show some common method:
a = [12, 13, 13, 14]
a.count(13)
-> 2
a.index(14)
-> 3
a.reverse()
-> [14, 13, 13, 13]
b = [2, 1, 3 ,5, 4]
b.sort()
-> [1, 2, 3, 4, 5]
b.sort(reverse = True)
-> [5, 4, 3, 2, 1]
22. In python , there are also have an important type tuple
if you define a tuple , you can't change it , but if it is list ,you can modify ,insert ,delete value.
now that we have list , why we need tuple , i guess , they are like array and mutablearray in oc.
tuple1 = (1,2,3,4,5,6,7)
tuple1[1]
-> 2
tuple1[:]
-> (1,2,3,4,5,6,7)
but we can't modify it , such as:
tuple1[1] = 10
-> error
now we can some special thing :
temp = (1)
-> 1
type(temp)
-> int
temp = 1, 2
type(temp)
-> tuple
so if tuple is one number , we should user temp = (1,) or temp = 1, then type(temp) can get tuple
now we can see an interesting question:
6 * (6) -> 36
6 * (6,) -> (6, 6, 6, 6, 6, 6)
how to add a new value to duple:
such as:
temp = ('roy' ,'wyg' ,'tom')
temp = temp[:2] + ('jim',) + temp[2:]
-> ('roy' ,'wyg', 'jim' ,'tom')
we can use del temp to delete all temp
duple we can user + , * , = , in , not in , and , or etc.
- In python , str is an important type. it is similar to duple.
str1 = 'my name is roy'
str1[:6]
-> 'my nam'
str1[3]
-> n
str1[:6] + 'ttt' + str1[6:]
-> 'my namttte is roy'
str2 = 'roy'
str2.capitalize()
-> 'Roy'
str3 = 'ROY'
str3.casefold()
-> 'roy'
str4 = 'roy'
str4.center(6)
-> ' roy '
str5 = 'royroy'
str5.count('y')
-> 2
str6 = 'roy'
str6.endswith('oy')
-> True
str7 = 'Itlovetyou'
str7.expandtabs()
->
'I love you'
str8 = 'abcd'
str8.find('d')
-> 3
str8.find('e')
-> -1
str8.index('d')
-> 3
str8.index('e')
-> error
there are also other method:
isalnum() #如果字符串中至少有一个字符并且所有字符都是字母或数字返回True
isalpha() #如果字符串中至少有一个字符并且所有字符都是字母返回True
isdecimal()#如果字符串只包含十进制数字返回True
isdigit() #如果字符串中只包含数字返回True
islower() #如果字符串中至少包含一个区分大小写的字符,并且这些字符都是小写,返回True
isnumeric() #如果字符串中只包含数字字符,返回True
isspace() #如果字符串中只包含空格,返回True
istitle() #如果字符串是标题化,所有单词大写开始,其余小写,返回True
isupper()
#如果字符串中至少包含一个区分大小写的字符,并且这些字符都是大写,返回True
lstrip() #去掉字符串中左边所有空格
rstrip() #去掉字符串右边所有空格
join(sub) #以字符串作为分隔符,插入到sub中所有的字符之间
ljust(width) #返回一个左对齐字符串,并使用空格填充至width长度
lower() #大写字符转化为小写
partition(sub) #找到子字符串sub,把字符串分割一个3元组,如不包含sub,则返回元字符串
replace(old,new[,count]) #把old换成new,如果count指定,则替换不超过count次
rfind(sub,[,start,[,end]) #类find,从右边开始查找
rindex(sub,[,start],[,end]) #类index,从右边开始
rpartition(sub) #类似partition(),从右边开始查找
rjust(width) #右对齐
split(sep = None,maxsplit = -1) #不带参数是以空格为分隔符,如maxsplit有设置,则分割成maxsplit个子字符串,返回列表
splitlines(([keepends])) #按照n分隔,返回一个包含各行作为元素的列表,如制定keepends,返回前keepends行
swapcase() #翻转字符串中的大小写
title() #返回标题话
startswith(prefix[,start][,ends]) #是否以prefix开始,返回 True
strip([chars]) #删除字符串前边和后边所有空格
upper()
translate(table) #替换字符
zfil(width) #右边对齐,前边0填充
range(stop)
me
bool()将给定参数转换为布尔类型,如果没有参数,返回False。bool是int的子类。
float or string -> int
类型转换
temp = input('input a num you
want:')
guess = int(temp)
if guess == 8:
print('you are right')
else:
print('you are wrong')
iter()用于生成迭代器
- In python , import module , such as if you want a rand num , range is 1-10 and type is int ,how to achieve it
next(iterator[,defaul]) 返回迭代器的下一个项目。
temp = 'roy'
str()将对象转化为适于阅读的形式
all(),any()的参数都是元组或列表,区别:all()如果所有元素都不是0、''、False或者iterable为空,返回True,否则返回False;any()如果所有元素为空、0、False则返回False,如果不都为空、0、False,则返回True;all()参数是空列表或空元组,返回True,any()返回False。
such as:
issubclass(B, A)用于判断B是否是A的子类,A、B都是类名
such as follow ,because indent error ,it will appear an error:
ord() 意义和chr()相反,以字符为参数,返回对应的ascii数值。
such as:
class A:
@classmethod
def cm(cls):
print('类方法调用者:', cls.__name__)
@staticmethod
def sm():
print('静态方法调用')
class B(A):
pass
A.cm()
B.cm()
A.sm()
B.sm()
Temp = 'wyg'
round(x[, n])返回浮点数的四舍五入,n表示小数点后预留位数,默认为0.
- In python , if you want to use ' in a string ,you can user escape charcters :
super() 用于调用父类的一个方法
a = '26' b = int(a) print(b) -> 26
complex()用于创建一个复数,形如real+imag*j
such as :
dict() 生成字典,dict()生成空字典,dict(a='e', b='f', c='g'),传入关键字,{'a':'e', 'b':'f', 'c':'g'},dict(zip(['one', 'two', 'three'], [1, 2, 3])),dict([('one', 1), ('two', 2), ('three', 3)])
randnum = random.randint(1,10)
setattr(object, name, value),getattr(object, name)用于设置和获取属性,该属性必须存在。hasattr(object, name)用于判断属性是否存在。
c:
eg。
result is :
a = 3.14 b = int(a) print(b) -> 3
the result is :
dir(__builtins__)
- In python, you should be care to indent, if not , it will appear a lots error.
编辑:编程 本文来源:数据类型由三部分组成身份(id)、类型(type)
关键词: