文章目录
字典表dict
声明
(健:值)
d = {'ISBN':'23423424','Title':'Python入门','Price':39.00}
赋值
d['Author'] = 'Jerry'
dict(健=值)
emp = dict(name = 'Mike',age = 20,job = 'dev')
操作
获取
#键的值是分大小写的,用d.get如果获取不到不会抛异常
d.get('price')
#d.get可以设置默认值
d.get('price',0.0)
d[‘键’]
d['Title']
d['Price']
d.get(‘键’,默认值)
合并
用d.update()
de p = {'department':'技术部'}
emp.update(dep)
弹出
emp.pop('age')
排序
属性
keys()
emp.keys()
emp.values()
for k in emp.keys()
print(k)
for v in emp.values()
print(v)
values()
items()
emp.items()
for k,v in emp.items():
print('{}'=>'{}'.format(k,v))
排序
- 将keys()放入列表
d = {'a':1,'b':2,'c':3,'d':4}
ks = d.keys()
ks = list(d.keys())
ks.sort()
for k in ks:
print(d.get(k))
- .sorted() 全局函数
ks = d.keys()
for k in sorted(ks):
print(k,d.get(k))
嵌套
emp = {'age':20,'name':{'firstname':'Jerry','lastname':'Lee'},'dep':'行政部'}
emp.get('name')
emp['name']['firstname']
元组tuple
特性
任意对象有序集合
通过下表访问
属“不可变”类型
长度固定,任意类型,任意嵌套
声明
用圆括号声明
#用圆括号声明
(1,2)
t = (1,2,3,4)
for x in t:
print(x**2)
res = []
for x in t:
res.append(x**2)
#推导
res = [x**2 for x in t]
index(val):查找索引
t.index(3)
count(val):统计数量
t.count(3)
nametuple
from collections import namedtuple
Employee = namedtuple('Employee',['name','age','department','salary'])
jerry = Employee('Jerry',age=30,department='财务部',salary=9000.00)
jerry.name
jerry.salary
文件
基本语法
file = open(‘文件名’,mode)
mode
- r 读
- w 写
- a 增加
- b 二进制
- ‘+’ 可读可写
myfile = open('hello.txt','w')
myfile.write('优品课堂\n')
myfile.write('helloworld\n')
myfile.close()
f= open('hello.txt')
f.read()#.read()相当于指针,读取所有
f = open('hello.txt')
f.readline()#逐行读取
# 打印所有行
l = open('hello.txt').readlines()
for line in l:
print(line)
f = open('course.txt','w',encoding='utf-8')
f.write('优品课堂 Python教程\n')
f.write('www.codeclassroom.com')
f.close()
操作
read()
realine()
readlines()
close()
x,y,z = 1,2,3
l = [1,2,3]
f = open('datafile.txt','w')
f.write('{}','{}','{}'.format(x,y,z))
f.write(str(l))
f.close()
chars = open('datafile.txt').read()
pickle存取Python对象
pickle存储为二进制,状态可还原
dump(对象,目标文件)
d= {'a':1,'b':2}
f = open('datafile.pkl','wb')
import pickle
pickle.dump(d,f)
f.close()
load(文件)
open('datafile.pkl','rb').read()
f = open('datafile.pkl','rb')
data = pickleload(f)
注意:
with open('course.txt') as f:
for line in f.readlines():
print(line)
#自动跳出,不需要写f.close()
汇总
集合
序列
可变
列表list
不可变
字符串str
元组tuple
字节数组
映射
字典表 dict
集合
Set
数字
整型
int
boolean
...
浮点型
float
Deciaml 高精度