字典(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)的更多相关文章

  1. 3.Python3标准库--数据结构

    (一)enum:枚举类型 import enum ''' enum模块定义了一个提供迭代和比较功能的枚举类型.可以用这个为值创建明确定义的符号,而不是使用字面量整数或字符串 ''' 1.创建枚举 im ...

  2. 简明Python3教程 11.数据结构

    简介 数据结构基本上就是 – 可以将一些数据结合到一起的结构,换言之用于存储一组相关的数据. python拥有4种内建数据结构 – 列表,元组(tuple),字典和集合. 我们将看到如何它们,它们又是 ...

  3. 王霸雄图荣华敝屣,谈笑间尽归尘土|基于Python3双队列数据结构搭建股票/外汇交易匹配撮合系统

    原文转载自「刘悦的技术博客」https://v3u.cn/a_id_192 如果你爱他,那么送他去股市,因为那里是天堂:如果你恨他,送他去股市,因为那里是地狱. 在过去的一年里,新冠疫情持续冲击世界经 ...

  4. Python3.5入门学习记录-File

    在Python中,操作文件对象使用open函数来创建,下表列出了常用的操作file的函数: 序号 方法及描述 1.file.close() 关闭文件.关闭后文件不能再进行读写操作. 2.file.fl ...

  5. Python3 print()函数sep,end,file参数用法练习

    来自builtins.py:def print(self, *args, sep=' ', end='\n', file=None): # known special case of print &q ...

  6. Python学习(四)数据结构 —— dict

    词典类型 dict 字典由键(key)和对应值(value)成对组成.字典也被称作关联数组或哈希表. dict 赋值 dict 整体放在花括号{}中,每个键与值用冒号隔开(:),每对用逗号分割: d ...

  7. python3.x Day3 文件编码

    文件编码: 知识点不多,但及其重要,python2和python3处理机制还有不同点,需要注意. 首先: 编码.数据类型,完全不同的概念. 文件编码:可以遵循开发环境.可以自行设定. 变量值编码:py ...

  8. python3(七)dict list

    # dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度. # dict内部存放的顺序和key放入的顺序是没有关系的 # 根据同学的名字 ...

  9. (04)-Python3之--字典(dict)操作

    1.定义 字典的关键字:dict 字典由多个键和其对应的值构成的 键-值 对组成,每个键值对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中. {key1:value1 ...

随机推荐

  1. html5之history对象 控制浏览器前进或后退事件

    一.摘要: 总结用history对象操作浏览器的历史记录的方法,在项目中使用的是mui框架,总结中包括我在实际项目中遇到的问题. 二.总结: 实现效果: 实现代码: 上面的编辑页面加载的时候就要先调用 ...

  2. 无法打开登录所请求的数据库 "xxx"登录失败用户 'NT AUTHORITY\NETWORK SERVICE'

    解决:添加用户,选择NT AUTHORITY\SYSTEM登录名,选择当前数据库的架构. 勾选架构 勾选成员身份.如果不勾选,也会报异常:拒绝了对对象 'FW_ORG' (数据库 'ZW_DWSJ', ...

  3. 1001. 害死人不偿命的(3n+1)猜想 (15)

    1001. 害死人不偿命的(3n+1)猜想 (15) 较简单,直接代码实现: #include <cstdio> int main() { int n; scanf("%d&qu ...

  4. 黄聪:HtmlAgilityPack中SelectSingleNode的XPath和CSS选择器

    XPath和CSS选择器 原文:http://ejohn.org/blog/xpath-css-selectors 最近,我做了很多工作来实现一个同时支持XPath和CSS 3的解析器,令我惊讶的是: ...

  5. 可重入锁 公平锁 读写锁、CLH队列、CLH队列锁、自旋锁、排队自旋锁、MCS锁、CLH锁

    1.可重入锁 如果锁具备可重入性,则称作为可重入锁. ========================================== (转)可重入和不可重入 2011-10-04 21:38 这 ...

  6. JVM实用参数(七)CMS收集器

    HotSpot JVM的并发标记清理收集器(CMS收集器)的主要目标就是:低应用停顿时间.该目标对于大多数交互式应用很重要,比如web应用.在我们看一下有关JVM的参数之前,让我们简要回顾CMS收集器 ...

  7. H5的一些小问题

    [每日壹闻]常用HTML代码解释-------六.歌曲代码(1):在这组代码中,不必管它是mms.http.rtsp,只要看尾缀是asf.wma.wmv.wmv.rm都可适用下面的代码:1. 手动播放 ...

  8. Model View Controller

    On the iPhone or iPod touch, a modal view controller takes over the entire screen. This is the defau ...

  9. C语言fmod()函数:对浮点数取模(求余)

    头文件:#include <math.h> fmod() 用来对浮点数进行取模(求余),其原型为:    double fmod (double x); 设返回值为 ret,那么 x = ...

  10. os.path 大全

    os.path.abspath(path) #返回绝对路径 os.path.basename(path) #返回一个路径的最后一个组成部分 os.path.commonprefix(list) #返回 ...