数据类型小结
一、列表,元组
列表:用于存储多个数据,是可以迭代的,可变数据类型。
切片
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 >>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"] 2 >>> names[1:4] #取下标1至下标4之间的数字,包括1,不包括4 3 ['Tenglan', 'Eric', 'Rain'] 4 >>> names[1:-1] #取下标1至-1的值,不包括-1 5 ['Tenglan', 'Eric', 'Rain', 'Tom'] 6 >>> names[0:3] 7 ['Alex', 'Tenglan', 'Eric'] 8 >>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样 9 ['Alex', 'Tenglan', 'Eric'] 10 >>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写 11 ['Rain', 'Tom', 'Amy'] 12 >>> names[3:-1] #这样-1就不会被包含了 13 ['Rain', 'Tom'] 14 >>> names[0::2] #后面的2是代表,每隔一个元素,就取一个 15 ['Alex', 'Eric', 'Tom'] 16 >>> names[::2] #和上句效果一样 17 ['Alex', 'Eric', 'Tom']
追加
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 >>> names 2 ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy'] 3 >>> names.append("我是新来的") 4 >>> names 5 ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
插入
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 >>> names 2 ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的'] 3 >>> names.insert(2,"强行从Eric前面插入") 4 >>> names 5 ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的'] 6 7 >>> names.insert(5,"从eric后面插入试试新姿势") 8 >>> names 9 ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
修改
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 >>> names 2 ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的'] 3 >>> names[2] = "该换人了" 4 >>> names 5 ['Alex', 'Tenglan', '该换人了', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
删除
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 >>> del names[2] 2 >>> names 3 ['Alex', 'Tenglan', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的'] 4 >>> del names[4] 5 >>> names 6 ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的'] 7 >>> 8 >>> names.remove("Eric") #删除指定元素 9 >>> names 10 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', '我是新来的'] 11 >>> names.pop() #删除列表最后一个值 12 '我是新来的' 13 >>> names 14 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
扩展
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 >>> names 2 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy'] 3 >>> b = [1,2,3] 4 >>> names.extend(b) 5 >>> names 6 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
拷贝
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 >>> names 2 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3] 3 4 >>> name_copy = names.copy() 5 >>> name_copy 6 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
统计
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 >>> names 2 ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3] 3 >>> names.count("Amy") 4 2
排序、翻转
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 >>> names 2 ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3] 3 >>> names.sort() #排序 4 Traceback (most recent call last): 5 File "<stdin>", line 1, in <module> 6 TypeError: unorderable types: int() < str() #3.0里不同数据类型不能放在一起排序了,擦 7 >>> names[-3] = '1' 8 >>> names[-2] = '2' 9 >>> names[-1] = '3' 10 >>> names 11 ['Alex', 'Amy', 'Amy', 'Tenglan', 'Tom', '1', '2', '3'] 12 >>> names.sort() 13 >>> names 14 ['1', '2', '3', 'Alex', 'Amy', 'Amy', 'Tenglan', 'Tom'] 15 16 >>> names.reverse() #反转 17 >>> names 18 ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']
获取下标
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 >>> names 2 ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1'] 3 >>> names.index("Amy") 4 2 #只返回找到的第一个下标
元组跟列表类似,但是不可变数据类型,即不能修改,可以通过重新赋值来修改(list)
二、字符串
属于不可修改类型,一般是加了双引。其中双引和单引并没有什么区别,主要用来区别字符串内多个引号,如果需要转义的字符过多可以使用r(引号,转义符无效)
a=r"aswerw$%!&sad"
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 name.capitalize() 首字母大写 2 name.casefold() 大写全部变小写 3 name.center(50,"-") 输出 '---------------------Alex Li----------------------' 4 name.count('lex') 统计 lex出现次数 5 name.encode() 将字符串编码成bytes格式 6 name.endswith("Li") 判断字符串是否以 Li结尾 7 "Alex\tLi".expandtabs(10) 输出'Alex Li', 将\t转换成多长的空格 8 name.find('A') 查找A,找到返回其索引, 找不到返回-1 9 10 format : 11 >>> msg = "my name is {}, and age is {}" 12 >>> msg.format("alex",22) 13 'my name is alex, and age is 22' 14 >>> msg = "my name is {1}, and age is {0}" 15 >>> msg.format("alex",22) 16 'my name is 22, and age is alex' 17 >>> msg = "my name is {name}, and age is {age}" 18 >>> msg.format(age=22,name="ale") 19 'my name is ale, and age is 22' 20 format_map 21 >>> msg.format_map({'name':'alex','age':22}) 22 'my name is alex, and age is 22' 23 24 25 msg.index('a') 返回a所在字符串的索引 26 '9aA'.isalnum() True 27 28 '9'.isdigit() 是否整数 29 name.isnumeric 30 name.isprintable 31 name.isspace 32 name.istitle 33 name.isupper 34 "|".join(['alex','jack','rain']) 35 'alex|jack|rain' 36 37 38 maketrans 39 >>> intab = "aeiou" #This is the string having actual characters. 40 >>> outtab = "12345" #This is the string having corresponding mapping character 41 >>> trantab = str.maketrans(intab, outtab) 42 >>> 43 >>> str = "this is string example....wow!!!" 44 >>> str.translate(trantab) 45 'th3s 3s str3ng 2x1mpl2....w4w!!!' 46 47 msg.partition('is') 输出 ('my name ', 'is', ' {name}, and age is {age}') 48 49 >>> "alex li, chinese name is lijie".replace("li","LI",1) 50 'alex LI, chinese name is lijie' 51 52 msg.swapcase 大小写互换 53 54 55 >>> msg.zfill(40) 56 '00000my name is {name}, and age is {age}' 57 58 59 60 >>> n4.ljust(40,"-") 61 'Hello 2orld-----------------------------' 62 >>> n4.rjust(40,"-") 63 '-----------------------------Hello 2orld' 64 65 66 >>> b="ddefdsdff_哈哈" 67 >>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则 68 True
三、字典
字典是key和value的对应值,即称为键值对。
key值唯一存在,并且无序。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
info = { 'stu1101': "TengLan Wu", 'stu1102': "LongZe Luola", 'stu1103': "XiaoZe Maliya", }
增加
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
>>> info["stu1104"] = "苍井空" >>> info {'stu1102': 'LongZe Luola', 'stu1104': '苍井空', 'stu1103': 'XiaoZe Maliya', 'stu1101': 'TengLan Wu'}
修改
>>> info['stu1101'] = "武藤兰" >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'}
删除
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 >>> info 2 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'} 3 >>> info.pop("stu1101") #标准删除姿势 4 '武藤兰' 5 >>> info 6 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} 7 >>> del info['stu1103'] #换个姿势删除 8 >>> info 9 {'stu1102': 'LongZe Luola'} 10 >>> 11 >>> 12 >>> 13 >>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} 14 >>> info 15 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} #随机删除 16 >>> info.popitem() 17 ('stu1102', 'LongZe Luola') 18 >>> info 19 {'stu1103': 'XiaoZe Maliya'}
查找
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 >>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} 2 >>> 3 >>> "stu1102" in info #标准用法 4 True 5 >>> info.get("stu1102") #获取 6 'LongZe Luola' 7 >>> info["stu1102"] #同上,但是看下面 8 'LongZe Luola' 9 >>> info["stu1105"] #如果一个key不存在,就报错,get不会,不存在只返回None 10 Traceback (most recent call last): 11 File "<stdin>", line 1, in <module> 12 KeyError: 'stu1105'
多级嵌套
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 av_catalog = { 2 "欧美":{ 3 "www.youporn.com": ["很多免费的,世界最大的","质量一般"], 4 "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"], 5 "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"], 6 "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"] 7 }, 8 "日韩":{ 9 "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"] 10 }, 11 "大陆":{ 12 "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"] 13 } 14 } 15 16 av_catalog["大陆"]["1024"][1] += ",可以用爬虫爬下来" 17 print(av_catalog["大陆"]["1024"]) 18 #ouput 19 ['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']
换个姿势,再来一次
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #values 2 >>> info.values() 3 dict_values(['LongZe Luola', 'XiaoZe Maliya']) 4 5 #keys 6 >>> info.keys() 7 dict_keys(['stu1102', 'stu1103']) 8 9 10 #setdefault 11 >>> info.setdefault("stu1106","Alex") 12 'Alex' 13 >>> info 14 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} 15 >>> info.setdefault("stu1102","龙泽萝拉") 16 'LongZe Luola' 17 >>> info 18 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} 19 20 21 #update 22 >>> info 23 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} 24 >>> b = {1:2,3:4, "stu1102":"龙泽萝拉"} 25 >>> info.update(b) 26 >>> info 27 {'stu1102': '龙泽萝拉', 1: 2, 3: 4, 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} 28 29 #items 30 info.items() 31 dict_items([('stu1102', '龙泽萝拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')]) 32 33 34 #通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个 35 >>> dict.fromkeys([1,2,3],'testd') 36 {1: 'testd', 2: 'testd', 3: 'testd'} 37 38 #方法1 39 for key in info: 40 print(key,info[key]) 41 42 #方法2 43 for k,v in info.items(): #会先把dict转成list,数据里大时莫用 44 print(k,v)
三、集合
无序,去重。主要进行关系测试。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 s = set([3,5,9,10]) #创建一个数值集合 2 3 t = set("Hello") #创建一个唯一字符的集合 4 5 6 a = t | s # t 和 s的并集 7 8 b = t & s # t 和 s的交集 9 10 c = t – s # 求差集(项在t中,但不在s中) 11 12 d = t ^ s # 对称差集(项在t或s中,但不会同时出现在二者中) 13 14 15 16 基本操作: 17 18 t.add('x') # 添加一项 19 20 s.update([10,37,42]) # 在s中添加多项 21 22 23 24 使用remove()可以删除一项: 25 26 t.remove('H') 27 28 29 len(s) 30 set 的长度 31 32 x in s 33 测试 x 是否是 s 的成员 34 35 x not in s 36 测试 x 是否不是 s 的成员 37 38 s.issubset(t) 39 s <= t 40 测试是否 s 中的每一个元素都在 t 中 41 42 s.issuperset(t) 43 s >= t 44 测试是否 t 中的每一个元素都在 s 中 45 46 s.union(t) 47 s | t 48 返回一个新的 set 包含 s 和 t 中的每一个元素 49 50 s.intersection(t) 51 s & t 52 返回一个新的 set 包含 s 和 t 中的公共元素 53 54 s.difference(t) 55 s - t 56 返回一个新的 set 包含 s 中有但是 t 中没有的元素 57 58 s.symmetric_difference(t) 59 s ^ t 60 返回一个新的 set 包含 s 和 t 中不重复的元素 61 62 s.copy() 63 返回 set “s”的一个浅复制
购物车用使用字典:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 goods = [ 2 {"name": "电脑","price":1999}, 3 {"name": "鼠标","price":10}, 4 {"name": "游艇","price":20}, 5 {"name": "美女","price":998}, 6 ] 7 i=0#只用于循环 8 name=[]#创建一个所有的商品列表,用于判断用户选择是否在列表中 9 money=input("你有多少钱?")#总钱 10 money = int(money) 11 money_left=money#剩余的钱 12 my_good=goods 13 for j in my_good: 14 j['num']=0 15 while i < len(goods): 16 name.append(goods[i]["name"]) 17 print(i+1,goods[i]["name"],goods[i]["price"]) 18 i+=1 19 while True: 20 chioce =input("选一个吧") 21 if chioce.isdigit(): 22 chioce = int(chioce) 23 if chioce>4 or chioce <0: 24 print("你在开玩笑吗?再玩我试试") 25 else: 26 if money < int(goods[chioce-1]["price"]): 27 print("小屁孩,钱不带够也想买东西?") 28 continue 29 else: 30 my_good[chioce-1]["num"]+=1 31 money_left -=my_good[chioce-1]["price"] 32 print("你买了:",my_good[chioce-1]["name"], 33 "价钱为:",my_good[chioce-1]["price"], 34 "剩余钱:",money_left) 35 continue 36 elif chioce in name: 37 if money < int(goods[name.index(chioce)]["price"]): 38 print("小屁孩,钱不带够也想买东西?") 39 continue 40 else: 41 my_good[name.index(chioce)]["num"]+=1 42 money_left -=my_good[name.index(chioce)]["price"] 43 print("你买了:", my_good[name.index(chioce)]["name"], 44 "价钱为:", my_good[name.index(chioce)]["price"], 45 "剩余钱:", money_left) 46 elif chioce == "q": 47 print("赶紧结账走人,别耽误我做生意") 48 break 49 else: 50 print("别玩我,我不认识字,重输吧!!") 51 i=0 52 print("你买了") 53 print("%4s%6s%6s%4s%6s"%("编号","商品","单价","数量","合计")) 54 while i<4: 55 if my_good[i]["num"]!=0: 56 print("%4s%8s%7s%4s%10s" % 57 (i+1,my_good[i]["name"],my_good[i]["price"],my_good[i]["num"],my_good[i]["price"]*my_good[i]["num"])) 58 i+=1 59 print("剩余金钱",money_left)