day2-python基础2
本节内容
1、列表,元组的使用
2、字符串操作
3、字典操作
4、集合操作
5、文件操作
1、列表,元组的使用 |
列表是python常用的数据类型,通过列表实现对数据的存储、修改等操作。
定义列表
1 n2 = ['a','b','c','d'] #通过中括号存储数据赋予给n2
通过列表的下标取值
n2 = ['a','b','c','d'] print(n2[0]) print(n2[1]) print(n2[2]) print(n2[3])
切片
n2 = ['a','b','c','d'] print(n2[1:3]) #取下标1-3的值,包括1 'b'、不包括3 'd' #['b', 'c'] print(n2[:]) #取所有值 #['a', 'b', 'c', 'd'] print(n2[-1]) #取倒数第一的值 #d print(n2[0:3:1]) #一个一个值取0-3的值,但不包括3 'd'的值 #['a', 'b', 'c'] print(n2[0:3:2]) #两个两个值取0-3的值,但不包括3 'd'的值 #['a', 'c'] print(n2[-3:-1]) #取倒数第三至倒数第一的值,但是不包括-1 'd'的值 #['b', 'c'] print(n2[-3:]) #取倒数第三至倒数第一的值 #['b', 'c', 'd']
追加
n2 = ['a','b','c','d'] n2.append('new') print(n2) #['a', 'b', 'c', 'd', 'new']
插入
n2 = ['a','b','c','d'] n2.insert(2,'c2') print(n2) #['a', 'b', 'c2', 'c', 'd']
修改
n2 = ['a','b','c','d'] n2[2] = 'cc2' print(n2) #['a', 'b', 'cc2', 'd']
删除
n2 = ['a','b','c','d'] #n2[2] = 'cc2' n2.remove('c') #直接删除数据值 print(n2) #['a', 'b', 'd'] n2.pop(2) #通过下标删除 print(n2) #['a', 'b']
扩展
n2 = ['a','b','c','d'] n3 = ['e','f','g'] n2.extend(n3) print(n2) #['a', 'b', 'c', 'd', 'e', 'f', 'g']
拷贝
n2 = ['a','b','c','d'] n3 = n2.copy() print(n3) #['a', 'b', 'c', 'd']
统计
n2 = ['a','b','c','d','a','b','a'] print(n2.count('a')) #3
排序
n2 = ['a','b','c','d',1,2,3] #n2.sort() #print(n2) #TypeError: '<' not supported between instances of 'int' and 'str' #不支持不同的数据类型排序 n2[-3] = '1' n2[-2] = '2' n2[-1] = '3' n2.sort() print(n2) #['1', '2', '3', 'a', 'b', 'c', 'd']
获取下标
n2 = ['a','b','c','d','1','2','3'] print(n2.index('a')) #0 print(n2.index('1')) #4
元组
元组和列表差不多,都是存储一组数据,但是元组创建不能修改,所以也叫只读列表
n2 = ('a','b','c','d') #只有2个参数 print(n2) print(n2.index('a')) print(n2.count('a'))
2、字符串操作 |
name = 'chEn Miaoni Can no' print(name) print(name.capitalize()) #首字母大写 print(name.casefold()) #所有大写变小写 print(name.center(50,'-')) #输出----------------chEn Miaoni Can no---------------- print(name.count('no')) #统计‘no’出现的次数 print(name.encode()) #将字符串编码成bytes格式 print(name.endswith('no')) #判断字符串是否已‘no’结尾 print('my\tname'.expandtabs(5)) #my name将\t转换成5空字符串 print(name.find('n')) #查找n,找到返回其索引,找不到返回-1 #format msg = 'my name is {}, and age is {}' print(msg.format('chx',22)) msg = 'my name is {1}, and age is {0}' print(msg.format('chx',22)) msg = "my name is {name}, and age is {age}" print(msg.format(age=22,name='chx')) #format_map print(msg.format_map({'name':'chx','age':22})) print(msg.index('a')) #返回a所在字符串的索引 print('aldf'.isalnum()) #True print('9'.isdigit()) #是否整数 print(msg.swapcase()) #大小写互切换 print(msg.zfill(40)) #重左往右填满40字符串0000my name is {name}, and age is {age} print(msg.ljust(40,'-'))#my name is {name}, and age is {age}----- print(msg.rjust(40,'-'))#-----my name is {name}, and age is {age} b = 'slfjalf你好' print(b.isidentifier()) #检测字符串可否被当作标识符,即是否符合变量命名规则
3、字典操作 |
字典是一种key-value的数据类型,和字典书一样,可以通过首字母,笔画查找
info = { 'stull01': "tenglan wu", 'stull02': "LongZe luola", 'stull03': 'XiaoZe Maliya', 'stull04': 'fang bingbing', 'stull05': 'zhang ziyi', }
增加
info['stull06'] = '苍井空' print(info) #{'stull01': 'tenglan wu', 'stull02': 'LongZe luola', 'stull03': 'XiaoZe Maliya', 'stull04': 'fang bingbing', 'stull05': 'zhang ziyi', 'stull06': '苍井空'}
修改
info['stull01'] = '武藤兰' print(info) #{'stull01': '武藤兰', 'stull02': 'LongZe luola', 'stull03': 'XiaoZe Maliya', 'stull04': 'fang bingbing', 'stull05': 'zhang ziyi', 'stull06': '苍井空'}
删除
info.pop('stull01') print(info) #{'stull02': 'LongZe luola', 'stull03': 'XiaoZe Maliya', 'stull04': 'fang bingbing', 'stull05': 'zhang ziyi'} del info['stull03'] print(info) #{'stull02': 'LongZe luola', 'stull04': 'fang bingbing', 'stull05': 'zhang ziyi'} info.popitem() #随机删除 print(info) #{'stull02': 'LongZe luola', 'stull04': 'fang bingbing'}
查找
info = { 'stull01': "tenglan wu", 'stull02': "LongZe luola", 'stull03': 'XiaoZe Maliya', 'stull04': 'fang bingbing', 'stull05': 'zhang ziyi', } print('stull02' in info) #存在返回真,否则为假 #True print(info.get('stull01')) #通过key获取value,不存在返回none #tenglan wu print(info['stull02']) #通过key获取value,不存在报错 #LongZe luola
多级字典嵌套及操作
av_catalog = { '欧美':{ 'www.youporn.com': ['很多免费的,世界是最大的','质量一般'], 'www.pornhub.com': ['很多免费的,也很大','质量比youporn高点'], 'letmedothistoyou.com': ['多是自拍,高质量图片很多','资源不多,更新慢'], 'x-art.com': ['质量很高,真的很高','全部收费,屌丝绕过'] }, '日韩':{ "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"] }, '大陆':{ "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"] } } av_catalog['大陆']['1024'][1] += ',可以用爬虫爬下来' #子字典增加 print(av_catalog['大陆']['1024']) #['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']
其他姿势
info = { 'stull01': "tenglan wu", 'stull02': "LongZe luola", 'stull03': 'XiaoZe Maliya', 'stull04': 'fang bingbing', 'stull05': 'zhang ziyi', } #values print(info.values()) #dict_values(['tenglan wu', 'LongZe luola', 'XiaoZe Maliya', 'fang bingbing', 'zhang ziyi']) #keys print(info.keys()) #dict_keys(['stull01', 'stull02', 'stull03', 'stull04', 'stull05']) #setdefualt info.setdefault('stull06','jingtian') print(info) #{'stull01': 'tenglan wu', 'stull02': 'LongZe luola', 'stull03': 'XiaoZe Maliya', 'stull04': 'fang bingbing', 'stull05': 'zhang ziyi', 'stull06': 'jingtian'} info.setdefault('stull02','泷泽萝拉') #设置了setdefault不会修改? print(info) #{'stull01': 'tenglan wu', 'stull02': 'LongZe luola', 'stull03': 'XiaoZe Maliya', 'stull04': 'fang bingbing', 'stull05': 'zhang ziyi', 'stull06': 'jingtian'} #update b = {1:2,3:4,'stull02':'泷泽萝拉'} info.update(b) print(info) #{'stull01': 'tenglan wu', 'stull02': '泷泽萝拉', 'stull03': 'XiaoZe Maliya', 'stull04': 'fang bingbing', 'stull05': 'zhang ziyi', 'stull06': 'jingtian', 1: 2, 3: 4} #items print(info.items()) #dict_items([('stull01', 'tenglan wu'), ('stull02', '泷泽萝拉'), ('stull03', 'XiaoZe Maliya'), ('stull04', 'fang bingbing'), ('stull05', 'zhang ziyi'), ('stull06', 'jingtian'), (1, 2), (3, 4)])
循环dict
#方法1 for i in av_catalog: print(i,av_catalog[i]) #方法2 for k,v in info.items(): #会先把dict转成list,数据里大时莫用 print(k,v)
4、集合操作 |
集合是一个无序,不重复的数据组合,它的主要作用如下:
- 去重,把一个列表去重,就自动去重了
- 关系测试,测试两组数据之前的交集、差集、并集等关系
s = [1,2,3,4,5,7,8,7,2,3] s = set(s) #将一个列表变成集合只需加上set print(s,type(s)) #{1, 2, 3, 4, 5, 7, 8} <class 'set'> t = set([1,2,33,4,2,' ']) print(s,t) #{1, 2, 3, 4, 5, 7, 8} {1, 2, 4, 33} #交集 print(s.intersection(t)) #{1, 2, 4} --s与t相同的部分打印出来 #并集 print(s.union(t)) #{1, 2, 3, 4, 5, 33, 7, 8} --去掉重复的值,将剩下的s,t相连起来 #差集 print(s.difference(t)) #{8, 3, 5, 7} --取出没在t里的s的值 print(t.difference(s)) #{33} --取出没在s里的t的值 t1 = set([1,2,33,4,2,44,' ']) #子集 print(t.issubset(t1)) #True --判断t1是否是t的子集 #父集 print(t.issuperset(t1)) #False --判断t1是否是t的父集 #对称差集 print(s.symmetric_difference(t)) #{33, 3, 5, 7, 8} --将s,t两边都不在对方的值取出 print(t.isdisjoint(t1)) #没搞懂?
5、文件操作 |
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 当我年少轻狂
##读取操作 f = open('t_file','r',encoding='utf-8') #utf-8编码,模式为读取的方式打开t_file文件 print(f.read()) print(f.tell()) #打印当前位置 print(f.readline()) #一行一行读取 print(f.readline()) print(f.readline()) print(f.tell()) #打印当前位置 print(f.seek(10)) #从哪个位置开始读 print(f.readline()) #一行一行读取 print(f.encoding) #打印编码 print(f.flush()) #刷新内存 f.close() #关闭文件 ##写入操作 f = open('t_file','w',encoding='utf-8') #utf-8编码,模式为w的方式打开t_file文件,w模式写入会覆盖原有内容 f.write('\n我爱北京天安门,\n') f = open('t_file','a',encoding='utf-8') #utf-8编码,模式为w的方式打开t_file文件,a模式追加
打开文件模式对比
- r,只读模式(默认)
- w,只写模式,写入会覆盖原有内容
- a,追加模式,可读,不存在写入,存在追加
‘+’表示可读写某个文件
- r+,读写,(可读,可写,可追加)
- w+,读写,(可读,存在内容删除写入)
- a+,读写,(可读,可写,不存在写入,存在追加)
其他操作
#显示进度条 import sys,time for i in range(100): sys.stdout.write('#') sys.stdout.flush() time.sleep(0.1) #在第9行后打印‘-------就是这么nb--------’,之后继续打印文件内容 count = 0 for line in f: if count ==9: print('-------------------------就是这么nb----------------------') count += 1 continue print(line.strip()) count += 1 f.close() #为避免打开后忘记关闭文件,可以通过管理上下文,即 with open('log','r') as f: