本章是学习前文提到的工具书《Python学习手册》针对基本数据类型的一个总结。
Python基本数据类型


数字
len(); //取长度
pow,abs,round int hex oct bin ;
oct函数把十进制数转换为八进制,hex函数把十进制数转换为十六进制,而bin把十进制数转换为二进制
str() repr();
math.pi math.e; math.sqrt(81);//开平方根
random.random() //随机数字生成器
random.choice() //随机选择器
表达式是处理数字的最基本的工具
Python表达式操作符


集合
x=set('spam');x={'s','p','a','m'};
y={'h','a','m'};
x&y={'a','m'}; x|y={'a','p','s','h','m'};
x-y={'p','s'}

其它类型: 复数,小数数字,分数类型,布尔值,占位符None
字符串
基本操作有合并,分片,索引等。

(是序列) 索引:S='spam'; S[0]='s',S[3]='m'; S[-1]='m',S[-2]='a';
分片:S[1:]='pam',S[0:3]='spa';

加法=合并 S+'xyz'='spamxyz',S*4='spamspamspamspam'
S.find('pa')=1 返回偏移; S.replace('pa','XYZ')='sXYZm';
S.upper()='SPAM'; //lower
S.isalpha()=True; //isdigit
line= 'aaa,bbb,ccc,dd'
line.splite(',')=['aaa','bbb','ccc','dd'];
line.rstrip();//移除右边的空格
格式化 '%s,eggs,and %s' %('spam','SPAM!') ='spam,eggs,and SPAM!'
'{0},eggs,and {1}'.format('spam','SPAM!')='spam,eggs,and SPAM!'
更高级的字符串格式化
1、基于字典的字符串格式化

2、添加键、属性和偏移量


补充:list(map(sum,M)) //map()函数对传入的list的每一个元素进行映射,返回一个新的映射之后的list
map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。又如:


ord()函数是chr()函数(对于8位的ASCII字符串)或unichr()函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的ASCII数值,或者Unicode数值,如果所给的Unicode字符超出了你的Python定义范围,则会引发一个TypeError的异常。
列表
(是序列) L=[123,'spam',1.23];len(L)=3; l[0]=123; L.index('spam')索引...
L.append('NI');L.extend([3,4,5]) ; L.insert(1,'toast');//插入 L.sort()排序;L.reverse()反转;
extend()和append()的区别:

L=['spam','eggs','ham']
L.pop(1);L.remove('eggs');del L[0];del L[1:]
嵌套 M=[ [1,2,3],
[4,5,6],
[7,8,9]] ;M[0]=[1,2,3]; M[1][2]=6;
列表解析 col2=[row[1] for row in M]=[2,5,8];
[row[1]+1 for row in M]=[3,6,9];
[row[1] for row in M if row[1]%2==0]=[2,8];
[M[i][i] for i in [0,1,2]] = [1,5,9];
G=(sum(row) for row in M),next(G)=6,next(G)=15,next(G)=24;...生成器
list(map(sum,M))=[6,15,24];[ord(x) for x in 'spaam']={115,112,97,97,109}; ...生成列表
{sum(row) for row in M}={6,15,24}; ...生成集合
{i:sum(M[i]) for i in range(3)}={0:6,1:15,2:24};...生成字典


字典
(是映射) D={'food':'spam','quantity':4,'color':'pink'}
D['food'] = 'spam';
D['quantity']+=1;D={'food':'spam','color':'pink','quantity':5}
D={};D['name']='Bob';D['job']='dev';D['age']=40;D={'age':40,'job':'dev','name':'Bob'}
嵌套 rec={'name':{'first':'Bob','last':'smith'},
'job':['dev','mgr'],
'age':40.5
}
键 D={'a':1,'b':2,'c':3};ks=list(D.keys())=['a','b','c'];
'f' in D = False
if not 'f' in D:
print('missing')
D={'spam':2,'ham':1,'eggs':3}
list(D.values())
输出:[3, 2, 1]
list(D.items())
输出: [('eggs', 3), ('spam', 2), ('ham', 1)]
D.get('spam');D.get('toast',88)
D2={'toast':4,'muffin':5};D.update(D2); D.pop('muffin')


创建字典的四种方法:



元组
(不可变的序列) T=(1,2,3,4);len(T)=4 ;T+(5,6)=(1,2,3,4,5,6);T[0]=1;
T.index(4)=3; T.count(4)=1;
T=('spam',3.0,[11,22,33]);


文件
f=open('data.txt','w');f.write('hello!\n');f.close();
f=file("/home/test/c.txt","r");
f.read();
date=open('data.bin','rb').read();
remove()/unlink() --- 删除文件
rename()/renames()---重命名文件
access()----------检验权限模式
chmod()-----------改变权限模式
chown()/lchown()-----改变 owner 和 group ID/功能相同, 但不会跟踪链接
umask()-------设置默认权限模式
open()---底层的操作系统 open (对于文件, 使用标准的内建 open() 函数)
read()/write()---根据文件描述符读取/写入数据
dup()/dup2()----复制文件描述符号,但是是复制到另一个文件描述符设备号
makedev()-----从 major 和 minor 设备号创建一个原始设备号
mkdir(path[,mode=0777])----创建目录
makedirs(name, mode=511)-----创建多层目录,
rmdir(path)------删除目录
removedirs(path)----删除多层目录
listdir(path)----列出指定目录的文件
getcwd() --- ---返回当前工作目录
chdir(path)-----改变当前工作目录
walk(top,topdown=True, onerror=None)---生成一个目录树下的所有文件名
chroot()----改变当前进程的根目录

网友评论