python3.5------day3-数据结构(dict,file)
字典(dict)
字典的定义:
字典的形式是以key:values。{key1,values,key2,values}
特性:
1、可以存放多个值
2、字典是无需的
3、字典的key是唯一,有去重功能
key的定义规则:
1、不可变的(数字,字符串,元组) 查看变量的内存为位置id
2、字典是唯一的
3、
hash判定是否可变
values定义:
任意类型
创建一个字典:
方法1
dict_1 = {'name':'zhangsan', 'age':22}
方法2:
# 方法2
dict4 = dict(name='zhangsan',age=22)
print(dict4)
方法3
# 方法3
dict5 = dict((('name','zhangsan'),('age',22)))
print(dict5)
方法4:
# 方法4
dict6 = dict({'name':'zhangsan','age':22})
print(dict6)
字典的增:
如果字典中没有对应的key,则增加,如果有对应的key,则覆盖
# 增
dict_1 = {'name':'zhangsan', 'age':22}
print(dict_1)
dict_1['Sex'] = 'male'
print(dict_1)
字典的删
# 删除
dict_1 = {'name':'zhangsan', 'age':22}
# 删除方法1
del dict_1['name']
print(dict_1)
结果:
{'age': 22} # 删除方法2:
dict_1.pop('name')
print(dict_1)
结果:
{'age': 22} # 删除方法3
dict_1.popitem() # 属于随机删除
print(dict_1)
结果:
{'age': 22}
字典的改
# 改
dict_1 = {'name':'zhangsan', 'age':22}
dict_1['name'] = 'lisi'
print(dict_1) 结果:
{'age': 22, 'name': 'lisi'}
字典的查
# 查
dict_1 = {'name':'zhangsan', 'age':22}
print(dict_1)
print(dict_1['name']) #此种方法,如果key不存在,将会报错,而get方法不存在不会报错
print(dict_1.get('name'))
结果:
{'age': 22, 'name': 'zhangsan'}
zhangsan
zhangsan
字典的遍历
dict_1 = {'name':'zhangsan', 'age':22}
# 方法1
for k in dict_1:
print(k,dict_1[k])
# 方法2
for k, v in dict_1.items():
print(k, v)
字典的其他方法
# keys方法
dict_1 = {'name':'zhangsan', 'age':22}
print(dict_1.keys()) # 遍历keys方法
for i in dict_1.keys():
print(i)
# vaules方法
print(dict_1.values())
for i in dict_1.values():
print(i) # uptate方法
dict2 = {'key':1, 'key2':2}
dict_1.update(dict2)
print(dict_1) # item方法
dict_1.items()
print(dict_1) # formkeys方法,快速生成一个字典
dict3 = dict.fromkeys([1, 2, 3], 'keys')
print(dict3) # setdefault方法
# 如果键在字典中,返回这个键所对应的值。如果键不在字典中,向字典 中插入这个键,并且以default为这个键的值,并返回 default。default的默认值为None
dict_1.setdefault("sex", "male")
print(dict_1)
三级菜单(精简版)的实现
menu = {
'北京': {
'海淀': {
'五道口': {
'soho': {},
'网易': {},
'google': {}
},
'中关村': {
'爱奇艺': {},
'汽车之家': {},
'youku': {},
},
'上地': {
'百度': {},
},
},
'昌平': {
'沙河': {
'老男孩': {},
'北航': {},
},
'天通苑': {},
'回龙观': {},
},
'朝阳': {},
'东城': {},
},
'上海': {
'闵行': {
"人民广场": {
'炸鸡店': {}
}
},
'闸北': {
'火车战': {
'携程': {}
}
},
'浦东': {},
},
'山东': {},
}
run_level = menu
last_level = []
while True:
for key in run_level:
print(key)
chose = input(">>").strip()
if len(chose) == 0:
continue
elif chose == 'b':
if len(chose) == 0:
break
run_level = last_level[-1]
last_level.pop()
elif chose == 'q':
break
elif chose not in run_level:
continue
last_level.append(run_level)
run_level = run_level[chose]
深拷贝和浅拷贝
浅拷贝,只是拷贝到最第一层
dic1 = {'name': 'alex', 'age': '', 'alex':['name','zhangsan','lisi']}
dic2 = dic1.copy()
print(dic1)
print(dic2)
dic2['alex'][0] = 'wangwu'
print(dic1)
print(dic2)
结果:
{'name': 'alex', 'alex': ['name', 'zhangsan', 'lisi'], 'age': ''}
{'name': 'alex', 'alex': ['name', 'zhangsan', 'lisi'], 'age': ''}
{'name': 'alex', 'alex': ['wangwu', 'zhangsan', 'lisi'], 'age': ''}
{'name': 'alex', 'alex': ['wangwu', 'zhangsan', 'lisi'], 'age': ''}
深拷贝
# 深拷贝需要用到copy模块,
import copy
dic1 = {'name': 'alex', 'age': '', 'alex':['name','zhangsan','lisi']}
dic2 = copy.deepcopy(dic1)
print(dic1)
print(dic2)
dic1['alex'][0] = 'wangwu'
print(dic1)
print(dic2) 结果:
{'age': '', 'name': 'alex', 'alex': ['name', 'zhangsan', 'lisi']}
{'age': '', 'name': 'alex', 'alex': ['name', 'zhangsan', 'lisi']}
{'age': '', 'name': 'alex', 'alex': ['wangwu', 'zhangsan', 'lisi']}
{'age': '', 'name': 'alex', 'alex': ['name', 'zhangsan', 'lisi']}
集合(set)
定义:由不同元素组成的集合,集合中是一组无序列的可hash值,可以作为字典的key
特性:
集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值
集合的创建
set = {1, 2, 3, 4, 5}
print(set)
print(type(set))
结果:
{1, 2, 3, 4, 5}
<class 'set'>
集合的常用方法:
set = {1, 2, 3, 4, 5}
print(set)
print(type(set))
结果:
{1, 2, 3, 4, 5}
<class 'set'>
set1 = {1, 2, 3, 4, 5}
set2 = {2, 3}
# 交集
print(set1 & set2)
# 结果:
{2, 3}
# 并集
print(set1 | set2)
# 结果:
{1, 2, 3, 4, 5}
# 差级
print(set1 - set2)
# 结果:
{1, 4, 5}
# 父级
print(set1 >= set2)
# 结果:
True
# 子集
print(set2 <= set1)
# 结果:
True
# 对称差级
print(set1 ^ set2)
# 结果:
{1, 4, 5}
# 删除
set1.pop() #随机删除
print(set1)
# 结果:
{2, 3, 4, 5}
set1.remove(5)
print(set1)
# 结果:
{2, 3, 4}
set1.discard(6)
print(set1)
# pop()方法随机删除
# remove()参数,如果删除的值不存在,报错,必须指定一个参数
# discard(),如果删除的值不存在,不会报错,删除事没有返回值 # 判定集合中是否有指定的值
if 'a' in set1:
print("存在")
else:
print("不存在")
#结果:
不存在
# 增加
set1.add("hello")
print(set1)
# 结果:
{2, 3, 4, 'hello'}
set1.update('abc')
print(set1)
# 结果:
{2, 3, 4, 'hello', 'c', 'b', 'a'}
集合的运算符
| 符号 | 意义 | 对应的集合方法 |
| & | 交集 |
intersection() |
| - | 差级 |
difference() |
| | | 并集 |
union() |
| >=,<= | 父级,子集 |
issubset() issuperset() |
| in | 在 | |
| not in | 不在 | |
| ^ | 对称差级 |
symmetric_difference() |
字符编码

文件
对文件的操作流程
1、打开文件,得到文件句柄并赋值给一个变量
2、通过文件句柄对文件进行操作
3、关闭文件
现有文件如下:
Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戏弄生命 视其为愚蠢的游戏
The way the evening breeze
就如夜晚的微风
May tease the candle flame
逗弄蜡烛的火苗
The thousand dreams I dreamed
我曾千万次梦见
The splendid things I planned
那些我计划的绚丽蓝图
I always built to last on weak and shifting sand
但我总是将之建筑在易逝的流沙上
I lived by night and shunned the naked light of day
我夜夜笙歌 逃避白昼赤裸的阳光
And only now I see how the time ran away
事到如今我才看清岁月是如何匆匆流逝
Yesterday when I was young
昨日当我年少轻狂
So many lovely songs were waiting to be sung
有那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
I ran so fast that time and youth at last ran out
我飞快地奔走 最终时光与青春消逝殆尽
I never stopped to think what life was all about
我从未停下脚步去思考生命的意义
And every conversation that I can now recall
如今回想起的所有对话
Concerned itself with me and nothing else at all
除了和我相关的 什么都记不得了
The game of love I played with arrogance and pride
我用自负和傲慢玩着爱情的游戏
And every flame I lit too quickly, quickly died
所有我点燃的火焰都熄灭得太快
The friends I made all somehow seemed to slip away
所有我交的朋友似乎都不知不觉地离开了
And only now I'm left alone to end the play, yeah
只剩我一个人在台上来结束这场闹剧
Oh, yesterday when I was young
噢 昨日当我年少轻狂
So many, many songs were waiting to be sung
有那么那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
There are so many songs in me that won't be sung
我有太多歌曲永远不会被唱起
I feel the bitter taste of tears upon my tongue
我尝到了舌尖泪水的苦涩滋味
The time has come for me to pay for yesterday
终于到了付出代价的时间 为了昨日
When I was young
当我年少轻狂
文件的基本操作
# open带个文件的方法,encoding指定打开文件的方法
f = open('test1', 'r', encoding='utf-8')
# readline方法,按行读取
first_line = f.readline()
print(first_line)
# 关闭文件
f.close()
打开文件的方法
| 模式 | 含义 |
| r | 只读模式打开,默认 |
| w | 只写模式,不可以读,不存在,则创建,存在则删除内容 |
| a | 追加模式,可读,不存在创建,存在则在后面追加内容 |
| r+ | 读写模式,可读,可写,可追加 |
| w+ | 写读模式 |
| a+ | 同a一样 |
| b | 以二进制形式打开文件,可与r、w、a结合使用 |
| U | 支持所有的换行符,将\r \n自动转换成\n , \r\n都表示换行 |
文件的基本操作
# 文件读取前5行
f = open('test1', 'r', encoding='utf-8')
count = 0
for line in f:
if count < 5:
print(f.readline())
count += 1 # readlines方法,一次读取所有的文件,并按行转换为列表形式
f = open('test1', 'r', encoding='utf-8')
line = f.readlines()
print(line)
f.closed # closed方法,判定文件是否关闭,关闭结果为真,反之为假
f = open('test1', 'r', encoding='utf-8')
line = f.readlines()
print(line)
print(f.closed) # read方法,一次读取整个文件,但是文件过大,并不能一次读取完不
f = open('test1', 'r', encoding='utf-8')
line = f.read()
print(line)
f.close() #
f = open('test', 'w', encoding='utf-8')
f.write('aaa')
f.flush() # name方法,显示文件名
print(f.name)
结果:
test # tell()方法,显示文件指针的位置,即文件读取到哪里的位置
f = open('test1', 'r+', encoding='utf-8')
line = f.readline()
print(line)
print(f.tell()) # truncate([size]) 保留文件从开始到指定的字符数,其他的都删除
f = open('test1', 'r+', encoding='utf-8')
f.truncate(20) # readable,判定文件是否可读
print(f.readable()) # writable,判定文件是否可写
print(f.writable()
文件的常用方法:
| 属性和方法 | 描述 |
| closed | 判断文件是否关闭,如果文件关闭,返回Ture |
| encoding | 显示文件的编码类型 |
| mode | 显示文件的打开模式 |
| name | 显示文件的名称 |
| newlines | 文件使用的换行模式 |
| flush() | 把缓存区的内容写入的磁盘,及强制刷新到磁盘 |
| close() | 关闭文件 |
| read([size]) | 从文件中读取size个文件内容,最为字符串返回 |
| readline([size]) | 从文件中读取一行,作为 字符串返回。如果执行size,表示每行每次读取的字节数,依然好读完整行的内容 |
| readlines([size]) | 把文件中的每行存取到列表中返回,如果指定size,表示每行每次读取的字节数 |
| seek(offset[, whence]) | 把文件指针移动到一个新的位置,offset表示相当于whence的位置。whenece用于设置相对位置的起点,0表示从文件的开头开始计算,1表示从当前位置开始计算,2表示从文件末尾开始计算,如果whenece省略,offset表示相对文件开头的位置 |
| tell | 返回文件指针当前的位置 |
| truncate([size]) | 删除size个字节后的内容 |
| write(str) | 把字符串str写入到文件 |
| writeline() | 把字符串序列写入到文件 |
修改文件内容:
test1文件内容
Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
代码:
with open('test2', 'w', encoding='utf-8') as f1:
with open('test1', 'r', encoding='utf-8') as f:
for line in f:
if '舌尖上的雨露' in line:
line = line.replace('舌尖上的雨露','舌头上的美味')
f1.write(line)
test2文件内容
Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌头上的美味
python3.5------day3-数据结构(dict,file)的更多相关文章
- 3.Python3标准库--数据结构
(一)enum:枚举类型 import enum ''' enum模块定义了一个提供迭代和比较功能的枚举类型.可以用这个为值创建明确定义的符号,而不是使用字面量整数或字符串 ''' 1.创建枚举 im ...
- 简明Python3教程 11.数据结构
简介 数据结构基本上就是 – 可以将一些数据结合到一起的结构,换言之用于存储一组相关的数据. python拥有4种内建数据结构 – 列表,元组(tuple),字典和集合. 我们将看到如何它们,它们又是 ...
- 王霸雄图荣华敝屣,谈笑间尽归尘土|基于Python3双队列数据结构搭建股票/外汇交易匹配撮合系统
原文转载自「刘悦的技术博客」https://v3u.cn/a_id_192 如果你爱他,那么送他去股市,因为那里是天堂:如果你恨他,送他去股市,因为那里是地狱. 在过去的一年里,新冠疫情持续冲击世界经 ...
- Python3.5入门学习记录-File
在Python中,操作文件对象使用open函数来创建,下表列出了常用的操作file的函数: 序号 方法及描述 1.file.close() 关闭文件.关闭后文件不能再进行读写操作. 2.file.fl ...
- Python3 print()函数sep,end,file参数用法练习
来自builtins.py:def print(self, *args, sep=' ', end='\n', file=None): # known special case of print &q ...
- Python学习(四)数据结构 —— dict
词典类型 dict 字典由键(key)和对应值(value)成对组成.字典也被称作关联数组或哈希表. dict 赋值 dict 整体放在花括号{}中,每个键与值用冒号隔开(:),每对用逗号分割: d ...
- python3.x Day3 文件编码
文件编码: 知识点不多,但及其重要,python2和python3处理机制还有不同点,需要注意. 首先: 编码.数据类型,完全不同的概念. 文件编码:可以遵循开发环境.可以自行设定. 变量值编码:py ...
- python3(七)dict list
# dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度. # dict内部存放的顺序和key放入的顺序是没有关系的 # 根据同学的名字 ...
- (04)-Python3之--字典(dict)操作
1.定义 字典的关键字:dict 字典由多个键和其对应的值构成的 键-值 对组成,每个键值对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中. {key1:value1 ...
随机推荐
- Python使用struct处理二进制
有的时候需要用python处理二进制数据,比如,存取文件,socket操作时.这时候,可以使用python的struct模块来完成.可以用 struct来处理c语言中的结构体. struct模块中最重 ...
- Struts1.x有两个execute方法,不要重写错哦HttpServletRequest才是对的(转)
Struts1.x 的 Action 有两个 execute 哦,小心搞错! by agate - Published: 2008-05-01 [9:42 下午] - Category: 程序编码 不 ...
- MySQL三大数据类型
- Node.js基础与实战
Node.js基础与实战 Node.jsJS高级进阶 NODE原理与解析 REPL交互环境 模块与NPM Buffer缓存区 fs文件操作 Stream流 TCP&UDP 异步编程 HTTP& ...
- HotSpot 自动内存管理笔记与实战
1.对象的创建 虚拟机遇到一条new指令时,首先会去检查这个指令的参数是否能在常量池中定位到一个类的符号引用,并且检查这个符号引用代表的类是否已被加载.解析和初始化过.如果没有,则必须先进行相应的类的 ...
- Allegro 快捷键设置
一.快捷键设置 Allegro可以通过修改env文件来设置快捷键,这对从其它软件如AD或PADS迁移过来的用户来说,可以沿用以前的操作习惯,还是很有意义的. Allegro的变量文件一共有2个:一个是 ...
- js实现的点击div区域外隐藏div区域(转)
首先看下JS的事件模型,JS事件模型为向上冒泡,如onclick事件在某一DOM元素被触发后,事件将跟随节点向上传播,直到有click事件绑定在某一父节点上,如果没有将直至文档的根. 阻止冒泡: 1. ...
- Java实现购物车功能:方式一:存放在session中.方式二:存储在数据库中
//将购物车产品加入到cookie中,方式同浏览记录.Java实现购物车,方式一(简易版):存储在session中.这种方式实现还不严谨,大家看的时候看思路即可.(1). JSP页面中,选择某一款产品 ...
- IO操作
/// <summary> /// 文件读写操作/// </summary> public partial class TestIO : DevComponents.DotNe ...
- 【原创】ORACLE常见使用问题解决
ORACLE常见使用问题解决 一.安装了oracle客户端后,发现plsql客户端找不到之前已经配置过的TNS连接信息 或许大家再使用ORACLE软件的过程中,经常会遇到这样的问题: 问题现象描述: ...