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': '22', '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': '22'}
{'name': 'alex', 'alex': ['name', 'zhangsan', 'lisi'], 'age': '22'}
{'name': 'alex', 'alex': ['wangwu', 'zhangsan', 'lisi'], 'age': '22'}
{'name': 'alex', 'alex': ['wangwu', 'zhangsan', 'lisi'], 'age': '22'}
 
深拷贝
#
# 深拷贝需要用到copy模块,
import copy
dic1 = {'name': 'alex', 'age': '22', 'alex':['name','zhangsan','lisi']}
dic2 = copy.deepcopy(dic1)
print(dic1)
print(dic2)
dic1['alex'][0] = 'wangwu'
print(dic1)
print(dic2)

结果:
{'age': '22', 'name': 'alex', 'alex': ['name', 'zhangsan', 'lisi']}
{'age': '22', 'name': 'alex', 'alex': ['name', 'zhangsan', 'lisi']}
{'age': '22', 'name': 'alex', 'alex': ['wangwu', 'zhangsan', 'lisi']}
{'age': '22', '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()

字符编码

python编码转换

文件

对文件的操作流程

  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 支持所有的换行符,将 自动转换成   , 都表示换行

文件的基本操作

# 文件读取前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
就如舌头上的美味
原文地址:https://www.cnblogs.com/alber/p/6009008.html