本节内容
- 列表、元组操作
- 字符串操作
- 字典操作
- 集合操作
- 文件操作
- 字符编码与转码
一、列表、元组操作
列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作
定义列表
>>> name = ['hongpeng',21,'ops']
通过下标访问列表中的元素,下标从0开始计数
>>> name[0]
'hongpeng'
>>> name[-1]#可以倒着取
'ops'
列表操作
(1)切片:取多个元素
>>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"] >>> names[1:4] #取下标1至下标4之间的数字,包括1,不包括4 ['Tenglan', 'Eric', 'Rain'] >>> names[1:-1] #取下标1至-1的值,不包括-1 ['Tenglan', 'Eric', 'Rain', 'Tom'] >>> names[0:3] ['Alex', 'Tenglan', 'Eric'] >>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样 ['Alex', 'Tenglan', 'Eric'] >>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写 ['Rain', 'Tom', 'Amy'] >>> names[3:-1] #这样-1就不会被包含了 ['Rain', 'Tom'] >>> names[0::2] #后面的2是代表,每隔一个元素,就取一个 ['Alex', 'Eric', 'Tom'] >>> names[::2] #和上句效果一样 ['Alex', 'Eric', 'Tom']
(2)追加
>>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy'] >>> names.append("我是新来的") >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
(3)插入
>>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的'] >>> names.insert(2,"强行从Eric前面插入") >>> names ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']>>> names.insert(5,"从eric后面插入试试新姿势") >>> names ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
(4)修改
>>> names ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的'] >>> names[2] = "该换人了" >>> names ['Alex', 'Tenglan', '该换人了', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
(5)删除
>>> del names[2] >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的'] >>> del names[4] >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的'] >>> >>> names.remove("Eric") #删除指定元素 >>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', '我是新来的'] >>> names.pop() #删除列表最后一个值 '我是新来的' >>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
(6)扩展
>>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy'] >>> b = [1,2,3] >>> names.extend(b) >>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
(7)copy
>>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]>>> name_copy = names.copy() >>> name_copy ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
name1 = [1,'hongpeng',['hello','world',8]]#列表中可以嵌套列表 name2 = name1.copy() print(name2) 输出[1, 'hongpeng', ['hello', 'world', 8]]name1 = [1,'hongpeng',['hello','world',8]] name2 = name1.copy() name2[2][2] = 88 print (name1) 输出[1, 'hongpeng', ['hello', 'world', 88]]
what the fuck!我明明把name2中的8替换为88,为什么name1中的8也变了????name1的值和name2的值有毛的关系啊??
原因是因为列表中如果还嵌套列表,那么copy只能copy第一层,第二层name1和name2都是共享一份数据,在内存中存在同一个地方。
想要copy之后改变name2二级列表里的值却不影响name1改怎么办呢?
只能用导入copy模块。
import copy name1 = [1,'hongpeng',['hello','world',8]] name2 = copy.deepcopy(name1) name2[2][2] = 88 print(name1) print(name2)输出 [1, 'hongpeng', ['hello', 'world', 8]] [1, 'hongpeng', ['hello', 'world', 88]]
哦也!!!
(8)统计
>>> names ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3] >>> names.count("Amy") 2
(9)获取下标
>>> names ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1'] >>> names.index("Amy") 2 #只返回找到的第一个下标
练习:
(1)
写一个列表,列表中包含本组成员 name = ['hong','peng','alex','tom','jack','dog','cat','tiger']
往中间插入两个其他组成员名字 name.insert(-2,'hello') name.insert(-2,'world')
取出第3-6的列表 name[2:7]
删除第7个人 name.remove('xx')
把刚才加入的其他组的人一次性删除 del name[4:6]
把组长名字加上备注 name[4] = "xxxxx"
要求每隔一个取一个 print(name[0::2])[x:x:x]步长
(2)name = [0,1,2,3,3,9,9,9],把列表中的9全部替换为999
name = [0,1,2,3,3,9,9,9] if 9 in name:num_of_ele = name.count(9)#统计9的个数for i in range(num_of_ele):position_of_ele = name.index(9)#循环得到含有9的索引name[position_of_ele] = 999#替换9为999print("[%s] 9 is/are in name,position:[%s]"%(num_of_ele,position_of_ele))
二、字符串操作
去空格
username = input('name:') if username.strip() == 'hongpeng':print('welcome')
分割
names = 'hong,peng,hello' name2 = names.split(",") print("|".join(name2))#按|把列表里的元素合成字符串
判断有无空格
name = "hong peng" print(''in name)
判断字符串中是否含有'o'
name = "hong peng" print name.find('o')
判断输入的是否是数字
password = '123' passwd = input('input your password:') if passwd.isdigit():print('welcome') else:print('wrong')
三、字典操作
创建字典
id_db = {111111111111:{'name':'jack','age':21,'addr':'jiangsu'},111111111112:{'name':'tom','age':22,'addr':'zhejiang'} }
取值
print(id_db[111111111112])
改
id_db[111111111111]['name'] = 'alex'
增
id_db[111111111111]['job'] = 'it'
删
id_db[111111111111].pop('addr')
查
a = id_db.get(111111111111) print(a)
查看元组中是否含key
a = 111111111113 in id_db print(a) #输出 Falseprint(dict.fromkeys([1,2],'dddd')) #输出 {1: 'dddd', 2: 'dddd'} #好像没什么卵用
查看元组中的key,value
for k ,v in id_db.items():#效率低print(k,v)for k in id_db:#效率高print(key,id_db[key])
小练习:
1.购物车(循环加元组)
__author__ = 'hongpeng' salary = input("Input your salary:") if salary.isdigit():salary = int(salary) else:exit("input must be a digit...")shop_car = [] dict_list = [('Iphone',6888),('Mac',10888),('cloth',300),('shoes',600),('coffee',30),('milk',3),('book',50)] print("welcome to hongpeng shopping mall".center(50,'-')) exit_flag = False while not exit_flag:print("我们有以下商品:".center(50,'-'))for item in enumerate(dict_list):index = item[0]d_name = item[1][0]d_price = item[1][1]print(index,'.',d_name,d_price)user_choice = input("[q=quit,c=check]what do you want to buy?")if user_choice.isdigit():user_choice = int(user_choice)if user_choice < len(dict_list):s_item = dict_list[user_choice]if s_item[1] < salary:salary -= s_item[1]shop_car.append(s_item)print("you have buy [%s] and your salary left [%s]"%(s_item[0],salary))else:print("you don't have enough money to buy [%s]"%s_item[0])else:if user_choice == 'q' or user_choice == 'quit':print("shopping list is as follows:".center(50,'*'))for item in shop_car:print(item)print("END".center(50,'*'))print("BYE")exit_flag = Trueelif user_choice == 'c' or user_choice == 'check':print("you have buy this things:".center(50,'*'))for item in shop_car:print(item)
2.三层菜单,选择MM(能返回上一级,每一级都能选择退出)
#_*_coding:utf-8_*_ __author__ = 'hongpeng' menu = {'江苏':{'苏州':['昆山MM','吴中MM'],'无锡':['江阴MM','锡山MM']},'北京':{'朝阳':['三里屯MM','工体MM'],'海淀':['北京电影学院MM','中央戏剧学院MM']},'湖北':{'武汉':['武汉大学MM']}} print(''' ----这位爷,我们这里有下面几个地方的姑娘,你想选哪个地区的呀?----''') exit_flag = False while not exit_flag:for index,k in enumerate(menu):print(index,k)choice_1 = (input('请选择编号:'))if choice_1.isdigit():choice_1 = int(choice_1)key_1 = list(menu.keys())[choice_1]#key_1 北京while not exit_flag:for index,k in enumerate(menu[key_1]):print (index,k)#0朝阳 1海淀choice_2 = (input('请选择编号:'))if choice_2.isdigit():choice_2 = int(choice_2)key_2 = list(menu[key_1].keys())[choice_2]#朝阳elif choice_2 == 'back':breakelif choice_2 == 'quit':exit_flag = Truewhile not exit_flag:for index,k in enumerate(menu[key_1][key_2]):print(index,k)#0三里屯 1工体choice_3 = (input('请选择编号:'))if choice_3.isdigit():choice_3 = int(choice_3)key_3 = menu[key_1][key_2][choice_3]print('你选择的是%s-%s-%s'%(key_1,key_2,key_3))exit_flag = Trueelif choice_3 == 'back':breakelif choice_3 == 'quit':exit_flag = True
3.购物三级菜单
shop_list = {'家电':{'冰箱':[('西门子',6000),('海尔',5000)],'空调':[('格力',3999),('美的',2999)]},'数码':{'手机':[('iphone6s',5888),('小米',1999)],'电脑':[('mac',10888),('Dell',6999)]},'居家':{'衣服':[('cloth',300),('shoes',666)],'牙膏':[('云南白药',38),('佳洁士',15)]}}print('welcome to shopping mall'.center(50,'-')) print('我们有以下分类,请选择:') for index,k in enumerate(shop_list):print(index,k) choice_1 = int(input('please choose:')) key_1 = list(shop_list.keys())[choice_1] for index,k in enumerate(shop_list[key_1]):print(index,k) choice_2 = int(input('continue choose:')) key_2 = list(shop_list[key_1].keys())[choice_2]for i in enumerate(shop_list[key_1][key_2]):index = i[0]d_name = i[1][0]d_price = i[1][1]print(index,'.',d_name,d_price)