python变量
1.摘要
- 列表(list)
- 元组(tuple)
- 字典(dict)
- 文件操作
- 命令行参数获取
2.列表
2.1列表定义
1 >>> names = [] #定义一个空列表 2 >>> 3 >>> names=["bigroot","scott","test","admin"] #定义一个列表并赋值 4 >>>
2.2列表的操作
- 赋值
- 追加
- 插入
- 删除
- 索引
- 切片
- 扩展
- 拷贝
- 统计
- 排序
- 反转
2.2.1赋值
1 >>> names=["bigroot","scott","test","admin"] 2 >>> names 3 ['bigroot', 'scott', 'test', 'admin'] 4 >>> 5 >>> names[1] = "SCOTT" #通过下标给列表中的位置为1的元素重新赋值 6 >>> names 7 ['bigroot', 'SCOTT', 'test', 'admin'] 8 >>>
2.2.2追加
1 >>> names.append("system") #在列表的最后添加一个新的元素 2 >>> names 3 ['bigroot', 'scott', 'test', 'admin', 'system'] 4 >>>
2.2.3插入
1 >>> names=["bigroot","scott","test","admin"] 2 >>> names.insert(2,"system") #指定将system插入列表中下表为2的位置 3 >>> names 4 ['bigroot', 'scott', 'system', 'test', 'admin'] 5 >>>
2.2.4删除
1 >>> names 2 ['bigroot', 'scott', 'system', 'test', 'admin'] 3 >>> del names[1] #删除指定下标的列表中的元素 4 >>> names 5 ['bigroot', 'system', 'test', 'admin'] 6 >>> 7 >>> del names #删除整个列表 8 >>> names 9 Traceback (most recent call last): 10 File "<pyshell#33>", line 1, in <module> 11 names 12 NameError: name 'names' is not defined 13 >>> 14 >>> 15 >>> 16 >>> names=['bigroot', 'scott', 'system', 'test', 'admin'] 17 >>> names.pop() #删除列表中最后一个元素,并返回被删除的元素 18 'admin' 19 >>> names 20 ['bigroot', 'scott', 'system', 'test'] 21 >>> names.pop() 22 'test' 23 >>> names 24 ['bigroot', 'scott', 'system'] 25 >>>
2.2.5索引
1 >>> names=['bigroot', 'scott', 'system', 'test', 'admin'] 2 >>> names.index("bigroot") #列表中元素的索引从0开始,可以通过索引找到对应的元素 3 0 4 >>> names[names.index("scott")] = "SCOTT" #通过索引修改元素的值 5 >>> names 6 ['bigroot', 'SCOTT', 'system', 'test', 'admin'] 7 >>> 8 >>> names.append("system") 9 >>> names 10 ['bigroot', 'SCOTT', 'system', 'test', 'admin', 'system'] 11 >>> names.index("system") #列表中存在多个重复值,索引默认只查找重复元素的第一个索引值 12 2 13 >>>
2.2.6切片
1 >>> names=['bigroot', 'scott', 'system', 'test', 'admin'] 2 >>> 3 >>> names[2:4] #取索引2~4的元素,不包含4,顾头不顾尾原则 4 ['system', 'test'] 5 >>> 6 >>> names[-3:-1] #取倒数第三个到倒数第二个的元素 7 ['system', 'test'] 8 >>> names[1:] #取索引值为1以后的所有元素 9 ['scott', 'system', 'test', 'admin'] 10 >>> names[:3] #取索引值3(不包含3)之前的元素值, 11 ['bigroot', 'scott', 'system'] 12 >>> 13 >>> names[:-1] 14 ['bigroot', 'scott', 'system', 'test'] 15 >>> 16 >>> names[1:] 17 ['scott', 'system', 'test', 'admin'] 18 >>> 19 >>> names[:3:1] #切片时默认步长为1 20 ['bigroot', 'scott', 'system'] 21 >>> names[:3:2] #切片的默认步长调整为2 22 ['bigroot', 'system'] 23 >>>
2.2.7扩展
1 >>> names 2 ['bigroot', 'scott', 'system', 'test', 'admin'] 3 >>> news=["smallroot","sys","root"] 4 >>> news 5 ['smallroot', 'sys', 'root'] 6 >>> 7 >>> names.extend(news) #将news中的所有元素加入names列表中 8 >>> names 9 ['bigroot', 'scott', 'system', 'test', 'admin', 'smallroot', 'sys', 'root'] 10 >>> news 11 ['smallroot', 'sys', 'root'] 12 >>>
2.2.8拷贝
1 >>> names=['bigroot', 'scott', 'system', 'test', 'admin'] 2 >>> news=names.copy() #列表拷贝 3 >>> test=names #列表赋值 4 >>> print("names:",id(names),"news:",id(news),"test:",id(test)) 5 names: 43708784 news: 43708704 test: 43708784 #拷贝列表相当于重新分配内存空间,赋值是只想相同的内存空间 6 >>>
2.2.9统计
1 >>> names=['bigroot', 'scott', 'system', 'test', 'admin',"scott"] 2 >>> names.count("scott") #统计列表中存在几个scott 3 2 4 >>>
2.2.10排序
1 >>> names 2 ['bigroot', 'scott', 'system', 'test', 'admin', 'scott'] 3 >>> names.sort() 4 >>> names 5 ['admin', 'bigroot', 'scott', 'scott', 'system', 'test'] 6 >>>
2.2.11反转
1 >>> names=['bigroot', 'scott', 'system', 'test', 'admin',"scott"] 2 >>> names.reverse() 3 >>> names 4 ['scott', 'admin', 'test', 'system', 'scott', 'bigroot'] 5 >>>
3.元组
3.元组
元组与列表类似但元组定义后不可以修改,故又称只读列表
3.1元组的定义
1 >>> names = ("scott","bigroot","system") 2 >>> names 3 ('scott', 'bigroot', 'system') 4 >>> names[1] = "SCOTT" #修改元组的内容报错 5 Traceback (most recent call last): 6 File "<pyshell#2>", line 1, in <module> 7 names[1] = "SCOTT" 8 TypeError: 'tuple' object does not support item assignment 9 >>>
3.2元组的操作
元组只有index和count两个方法
1 >>> names = ("scott","bigroot","system","sys","root","scott") 2 >>> names.index("scott") 3 0 4 >>> names.count("scott") 5 2 6 >>>
4.字典
4.1字典的定义
1 >>> names = { 2 "stdu1101":{"name":"Alex","age":22,"hobbie":"girl"}, 3 "stdu1102":"Jack", 4 "stdu1103":"rain", 5 } 6 >>> names 7 {'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 'stdu1102': 'Jack', 'stdu1103': 'rain'} 8 >>>
字典的特性
- 字典是无序的
- 字典的key值是唯一的
4.2字典的操作
4.2.1查询
1 >>> names = { 2 "stdu1101":{"name":"Alex","age":22,"hobbie":"girl"}, 3 "stdu1102":"Jack", 4 "stdu1103":"rain", 5 } 6 >>> 7 >>> names["stdu1101"] #通过key查询value的值 8 {'hobbie': 'girl', 'name': 'Alex', 'age': 22} 9 >>> 10 >>> names["stdu1101"]["name"] 11 'Alex' 12 >>> names["stud1104"] #查询的key值不存在会报错 13 Traceback (most recent call last): 14 File "<pyshell#34>", line 1, in <module> 15 names["stud1104"] 16 KeyError: 'stud1104' 17 >>> 18 >>> print(names.get("stdu1104")) #通过get方法,如果key值不存在返回None 19 None 20 >>> 21 >>> print(names.get("stdu1104","bigroot")) #通过get方法,如果key值不存在可自定义返回值 22 bigroot 23 >>>
4.2.2增加
1 >>> names 2 {'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 'stdu1102': 'Jack', 'stdu1103': 'rain'} 3 >>> names["stdu1104"] = ["bigroot",23,"dba"] 4 >>> names 5 {'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 'stdu1104': ['bigroot', 23, 'dba'], 'stdu1102': 'Jack', 'stdu1103': 'rain'} 6 >>>
4.2.3修改
1 >>> names 2 {'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 'stdu1104': ['bigroot', 23, 'dba'], 'stdu1102': 'Jack', 'stdu1103': 'rain'} 3 >>> names["stdu1104"][0] = "BIGROOT" 4 >>> names 5 {'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 'stdu1104': ['BIGROOT', 23, 'dba'], 'stdu1102': 'Jack', 'stdu1103': 'rain'} 6 >>>
4.2.4删除
1 >>> names 2 {'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 'stdu1104': ['BIGROOT', 23, 'dba'], 'stdu1102': 'Jack', 'stdu1103': 'rain'} 3 >>> print(names.pop("stdu1102")) #删除并返回被删除的元素 4 Jack 5 >>> names 6 {'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 'stdu1104': ['BIGROOT', 23, 'dba'], 'stdu1103': 'rain'} 7 >>> 8 >>> names.pop("stdu1102") #删除不存在的key值,程序报错 9 Traceback (most recent call last): 10 File "<pyshell#79>", line 1, in <module> 11 names.pop("stdu1102") 12 KeyError: 'stdu1102' 13 >>> 14 >>> names.pop("stdu1102","not found") #对于不存在的key进行pop删除,可自定义返回的结果 15 'not found' 16 >>> 17 >>> 18 >>> del names["stdu1101"] #使用del进行字典元素删除 19 >>> names 20 {'stdu1104': ['BIGROOT', 23, 'dba'], 'stdu1103': 'rain'} 21 >>>
4.2.5列表转换成字符串
1 >>> names = ["bigroot","jack","scott"] 2 >>> print(dict.fromkeys(names,1)) 3 {'jack': 1, 'bigroot': 1, 'scott': 1} 4 >>> 5 >>> n3 = dict.fromkeys(names,1) #将列表变成字典 6 >>> n3["jack"] = 2 #fromkeys(seq,value)当value整体修改时,会开辟一块新的内存 7 >>> n3 8 {'jack': 2, 'bigroot': 1, 'scott': 1} 9 >>> 10 >>> 11 >>> n4 = dict.fromkeys(names,[1,2,3]) 12 >>> n4 13 {'jack': [1, 2, 3], 'bigroot': [1, 2, 3], 'scott': [1, 2, 3]} 14 >>> n4["jack"][1] = 9 #fromkeys(seq,value)当value修改整体的一部分时,不会开辟新的内存, 15 >>> n4 #所有指向该内存的变量都会改变 16 {'jack': [1, 9, 3], 'bigroot': [1, 9, 3], 'scott': [1, 9, 3]} 17 >>> 18 >>> print(id(n4["jack"]),id(n4["scott"])) 19 58090760 58090760 20 >>>
1 >>> names = ["bigroot","jack","scott"] 2 >>> print(dict.fromkeys(names,1)) 3 {'jack': 1, 'bigroot': 1, 'scott': 1} 4 >>> 5 >>> n3 = dict.fromkeys(names,1) #将列表变成字典 6 >>> n3["jack"] = 2 #fromkeys(seq,value)当value整体修改时,会开辟一块新的内存 7 >>> n3 8 {'jack': 2, 'bigroot': 1, 'scott': 1} 9 >>> 10 >>> 11 >>> n4 = dict.fromkeys(names,[1,2,3]) 12 >>> n4 13 {'jack': [1, 2, 3], 'bigroot': [1, 2, 3], 'scott': [1, 2, 3]} 14 >>> n4["jack"][1] = 9 #fromkeys(seq,value)当value修改整体的一部分时,不会开辟新的内存, 15 >>> n4 #所有指向该内存的变量都会改变 16 {'jack': [1, 9, 3], 'bigroot': [1, 9, 3], 'scott': [1, 9, 3]} 17 >>> 18 >>> print(id(n4["jack"]),id(n4["scott"])) 19 58090760 58090760 20 >>> 21 >>> n4["jack"] = 10 22 >>> 23 >>> n4 24 {'jack': 10, 'bigroot': [1, 9, 3], 'scott': [1, 9, 3]} 25 >>> 26 >>> print(id(n4["jack"]),id(n4["scott"])) 27 2008154864 58090760 28 >>>
4.2.6字典变成元组
1 >>> names = { 2 'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 3 'stdu1102': 'Jack', 4 'stdu1103': 'rain' 5 } 6 >>> names.items() #将字典变成元组 7 dict_items([('stdu1101', {'age': 22, 'name': 'Alex', 'hobbie': 'girl'}), ('stdu1102', 'Jack'), ('stdu1103', 'rain')]) 8 >>>
注意:
1 names = { 2 'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 3 'stdu1102': 'Jack', 4 'stdu1103': 'rain' 5 } 6 7 8 for key in names: #效率高,不用转换 9 print(key,names[key]) 10 11 for k,v in names.items(): #效率低 12 print(k,v)
4.2.7keys和values
1 >>> names = { 2 'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 3 'stdu1102': 'Jack', 4 'stdu1103': 'rain' 5 } 6 >>> 7 >>> names.keys() #所有的key值 8 dict_keys(['stdu1101', 'stdu1102', 'stdu1103']) 9 >>> 10 >>> names.values() #所有的value值 11 dict_values([{'age': 22, 'name': 'Alex', 'hobbie': 'girl'}, 'Jack', 'rain']) 12 >>>
4.2.8随机删除
1 >>> names 2 {'stdu1101': {'age': 22, 'name': 'Alex', 'hobbie': 'girl'}, 'stdu1102': 'Jack', 'stdu1103': 'rain'} 3 >>> names.popitem() 4 ('stdu1101', {'age': 22, 'name': 'Alex', 'hobbie': 'girl'}) 5 >>> 6 >>> 7 >>> names.popitem() 8 ('stdu1102', 'Jack') 9 >>> 10 >>> names 11 {'stdu1103': 'rain'} 12 >>>
4.2.9setdefault方法
1 >>> names = { 2 'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 3 'stdu1102': 'Jack', 4 'stdu1103': 'rain' 5 } 6 >>> 7 >>> names 8 {'stdu1101': {'age': 22, 'name': 'Alex', 'hobbie': 'girl'}, 'stdu1102': 'Jack', 'stdu1103': 'rain'} 9 >>> 10 >>> names.setdefault("stdu1102") #key值存在时,返回key值对应的value值 11 'Jack' 12 >>> 13 >>> names.setdefault("stdu1105","system") #key值不存在时,将key值加入字典并赋值 14 'system' 15 >>> names 16 {'stdu1101': {'age': 22, 'name': 'Alex', 'hobbie': 'girl'}, 'stdu1105': 'system', 'stdu1102': 'Jack', 'stdu1103': 'rain'} 17 >>>
4.2.10合并
1 >>> names = { 2 'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 3 'stdu1102': 'Jack', 4 'stdu1103': 'rain' 5 } 6 >>> 7 >>> d1 = { 8 'stdu1102':"bigroot", 9 1:333, 10 2:444, 11 } 12 >>> names.update(d1) #与字典names中相同的key对应的value值被d1字典中的value值替换 13 >>> names 14 {'stdu1101': {'age': 22, 'name': 'Alex', 'hobbie': 'girl'}, 2: 444, 1: 333, 'stdu1102': 'bigroot', 'stdu1103': 'rain'} 15 >>> d1 16 {1: 333, 2: 444, 'stdu1102': 'bigroot'} 17 >>>
4.2.11复制
1 >>> names = { 2 'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 3 'stdu1102': 'Jack', 4 'stdu1103': 'rain' 5 } 6 >>> n2=names.copy() 7 >>> n2 8 {'stdu1101': {'age': 22, 'name': 'Alex', 'hobbie': 'girl'}, 'stdu1102': 'Jack', 'stdu1103': 'rain'} 9 >>> 10 >>> names["stdu1103"] = "RAIN" #第一层数据不会跟着变 11 >>> 12 >>> names 13 {'stdu1101': {'age': 22, 'name': 'Alex', 'hobbie': 'girl'}, 'stdu1102': 'Jack', 'stdu1103': 'RAIN'} 14 >>> 15 >>> n2 16 {'stdu1101': {'age': 22, 'name': 'Alex', 'hobbie': 'girl'}, 'stdu1102': 'Jack', 'stdu1103': 'rain'} 17 >>> 18 19 >>> names = { 20 'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 21 'stdu1102': 'Jack', 22 'stdu1103': 'rain' 23 } 24 >>> n2 = names.copy() 25 >>> n2 26 {'stdu1101': {'age': 22, 'name': 'Alex', 'hobbie': 'girl'}, 'stdu1102': 'Jack', 'stdu1103': 'rain'} 27 >>> names["stdu1101"]["age"] = 24 #第二层以及后面的数据都会跟着变 28 >>> names 29 {'stdu1101': {'age': 24, 'name': 'Alex', 'hobbie': 'girl'}, 'stdu1102': 'Jack', 'stdu1103': 'rain'} 30 >>> n2 31 {'stdu1101': {'age': 24, 'name': 'Alex', 'hobbie': 'girl'}, 'stdu1102': 'Jack', 'stdu1103': 'rain'} 32 >>>
注意:深copy
1 >>> names = { 2 'stdu1101': {'hobbie': 'girl', 'name': 'Alex', 'age': 22}, 3 'stdu1102': 'Jack', 4 'stdu1103': 'rain' 5 } 6 >>> 7 >>>import copy 8 >>> n3 = copy.deepcopy(names) #深copy,完全复制 9 >>> 10 >>> n3 11 {'stdu1101': {'hobbie': 'girl', 'age': 22, 'name': 'Alex'}, 'stdu1102': 'Jack', 'stdu1103': 'rain'} 12 >>> names["stdu1101"]["age"] = 24 13 >>> names 14 {'stdu1101': {'age': 24, 'name': 'Alex', 'hobbie': 'girl'}, 'stdu1102': 'Jack', 'stdu1103': 'rain'} 15 >>> 16 >>> n3 17 {'stdu1101': {'hobbie': 'girl', 'age': 22, 'name': 'Alex'}, 'stdu1102': 'Jack', 'stdu1103': 'rain'} 18 >>>
5.文件操作
原始文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game 10 我戏弄生命 视其为愚蠢的游戏 11 The way the evening breeze 12 就如夜晚的微风 13 May tease the candle flame 14 逗弄蜡烛的火苗 15 The thousand dreams I dreamed 16 我曾千万次梦见 17 The splendid things I planned 18 那些我计划的绚丽蓝图 19 I always built to last on weak and shifting sand 20 但我总是将之建筑在易逝的流沙上 21 I lived by night and shunned the naked light of day 22 我夜夜笙歌 逃避白昼赤裸的阳光 23 And only now I see how the time ran away 24 事到如今我才看清岁月是如何匆匆流逝 25 Yesterday when I was young 26 昨日当我年少轻狂 27 So many lovely songs were waiting to be sung 28 有那么多甜美的曲儿等我歌唱 29 So many wild pleasures lay in store for me 30 有那么多肆意的快乐等我享受 31 And so much pain my eyes refused to see 32 还有那么多痛苦 我的双眼却视而不见 33 I ran so fast that time and youth at last ran out 34 我飞快地奔走 最终时光与青春消逝殆尽 35 I never stopped to think what life was all about 36 我从未停下脚步去思考生命的意义 37 And every conversation that I can now recall 38 如今回想起的所有对话 39 Concerned itself with me and nothing else at all 40 除了和我相关的 什么都记不得了 41 The game of love I played with arrogance and pride 42 我用自负和傲慢玩着爱情的游戏 43 And every flame I lit too quickly, quickly died 44 所有我点燃的火焰都熄灭得太快 45 The friends I made all somehow seemed to slip away 46 所有我交的朋友似乎都不知不觉地离开了 47 And only now I'm left alone to end the play, yeah 48 只剩我一个人在台上来结束这场闹剧 49 Oh, yesterday when I was young 50 噢 昨日当我年少轻狂 51 So many, many songs were waiting to be sung 52 有那么那么多甜美的曲儿等我歌唱 53 So many wild pleasures lay in store for me 54 有那么多肆意的快乐等我享受 55 And so much pain my eyes refused to see 56 还有那么多痛苦 我的双眼却视而不见 57 There are so many songs in me that won't be sung 58 我有太多歌曲永远不会被唱起 59 I feel the bitter taste of tears upon my tongue 60 我尝到了舌尖泪水的苦涩滋味 61 The time has come for me to pay for yesterday 62 终于到了付出代价的时间 为了昨日 63 When I was young 64 当我年少轻狂
1 >>> print(open("lyric")) 2 <_io.TextIOWrapper name='lyric' mode='r' encoding='cp936'> #文件句柄 3 >>> 4 >>> print(open("lyric").read()) #文件字符编码与操作系统默认编码不同 5 Traceback (most recent call last): 6 File "<stdin>", line 1, in <module> 7 UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 106: illegal 8 multibyte sequence 9 >>> 10 >>> 11 >>> print(open("lyric",encoding="utf-8").read()) --成功打开文件 12 ...... 13 >>> data = open("lyric",encoding="utf-8").read() #文件对象打开读取完后,就消失 14 >>> print(data.replace("Somehow","HHHAAA")) 15 16 17 18 f=open("lyric",encoding="utf-8") 19 data= f.read() 20 data = data.replace("Somehow","HHHAAA") 21 print(data) 22 f.write(data) #报错,文件以读的模式打开不能写 23 24 #mode r=read,w=write,a=append 25 26 f=open("lyric",mode="w",encoding="utf-8") 27 data = data.replace("Somehow","HHHAAA") 28 print(data) 29 f.write(data) #报错以写模式打开不可以读,写模式会覆盖原来的 30 31 32 f=open("lyric",mode="w",encoding="utf-8") #创建 33 f.write("test") 34 f.write("test") 35 f.close() 36 37 f=open("lyric",mode="a",encoding="utf-8") #追加方式 38 f.write("test") 39 f.write("test") 40 f.close() 41 42 文件编辑的两种方式 43 方式一:将文件内容以w模式读到内存,关闭文件,在内存修改完毕后,重新以w模式打开文件写入,在关闭 44 f=open("lyric",mode="r",encoding="utf-8") 45 data=f.read() 46 data=data.replace("Somehow","HHHAAA") 47 f.close() 48 f=open("lyric",mode="w",encoding="utf-8") 49 f.write(data) 50 f.close() 51 52 53 方式一:打开新文件和旧文件 54 import os 55 f=open("lyric",mode="r",encoding="utf-8") 56 f_new=open("lyric_new",mode="w",encoding="utf-8") 57 for line in f: 58 if "Somehow" in line: 59 line = line.replace("Somehow","HHHAAA") 60 f_new.write(line) 61 f.close() 62 f_new.close() 63 os.remove("lyric") 64 os.rename("lyric_new","lyric")
6.命令行参数获取
1 import sys 2 3 name = sys.argv 4 print("name:",name)