700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Python学习笔记(基础知识第三篇:列表 元组 字典 集合)

Python学习笔记(基础知识第三篇:列表 元组 字典 集合)

时间:2023-01-12 17:20:50

相关推荐

Python学习笔记(基础知识第三篇:列表 元组 字典 集合)

一、列表

1.列表知识

定义一个空的列表,列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套)。

打印出第一个元素,列表索引值以0为开始值,-1为从末尾的开始位置。

列表可以使用+操作符进行拼接,使用*表示重复。

1.定义一个空的列表,列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套)。例如:

namelist = [‘小张’,‘xiaoli’,2,[1,2,3]]

2.打印出第一个元素,列表索引值以0为开始值,-1为从末尾的开始位置。例如:

print(namelist[0])

输出:小张

print(namelist[1:3])

输出:[‘xiaoli’,2]

3.列表可以使用+操作符进行拼接,使用*表示重复。

list = [1,2,3,4,5]

tylist = [‘hello’, ‘world’, [1,2,3]]

print(list+tylist)

输出:[1, 2, 3, 4, 5, ‘hello’, ‘world’, [1, 2, 3]]

4.for 和 while 与列表的结合使用

for:

# forfor name in namelist:print(name)

while:

# whilelength = len(namelist)i = 0while i < length:print(namelist[i])i += 1

2.增(.append, .extend, .insert)

append 在末尾添加一个元素:

a = [1,2]b = [3,4] a.append(b)# 将列表当作一个元素,加入列表中print(a)

extend 将b列表中的每一个元素,逐一加入到a列表中:

a = [1,2]b = [3,4] a.extend(b)# 将b列表中的每一个元素,逐一加入到a列表中print(a)

insert:指定下标位置插入元素

a = [0,1,2]a.insert(1,3) # insert:指定下标位置插入元素print(a) # 第一个变量表示下标,第二个表示元素(对象)

3.删(del, .pop, .remove)

del 在指定位置删除一个元素:

moviename = ['Harry Poter','Lord of the ring','Alice Wonderland','Flipped','Iron Man','Lord of the ring']del moviename[2]print(moviename)# 输出结果为['Harry Poter', 'Lord of the ring', 'Flipped', 'Iron Man', 'Lord of the ring']

.pop 默认弹出末尾最后一个元素:

moviename = ['Harry Poter','Lord of the ring','Alice Wonderland','Flipped','Iron Man','Lord of the ring']moviename.pop()print(moviename)# 输出结果为:['Harry Poter','Lord of the ring','Alice Wonderland','Flipped','Iron Man']moviename.pop(1)print(moviename)# 输出结果为:['Harry Poter', 'Alice Wonderland', 'Flipped', 'Iron Man', 'Lord of the ring']

.remove 直接删除指定内容:

moviename = ['Harry Poter','Lord of the ring','Alice Wonderland','Flipped','Iron Man','Lord of the ring']moviename.remove('Lord of the ring') # 只删除找到的第一个print(moviename)# 输出结果为:['Harry Poter', 'Alice Wonderland', 'Flipped', 'Iron Man', 'Lord of the ring']

4.改

修改指定下标的元素内容:

moviename = ['Harry Poter','Lord of the ring','Alice Wonderland','Flipped','Iron Man','Lord of the ring']moviename[1] = 'Inception' # 修改指定下标的元素内容print(moviename)# 输出结果为:['Harry Poter', 'Inception', 'Alice Wonderland', 'Flipped', 'Iron Man', 'Lord of the ring']

5.查(in, not in)

例1:

namelist = ['lucy','hellen']findname = input('please input the name you want to find:')if findname in namelist:print('we found the same name in the list')else:print('we didn\'t find the name.')

例2:

a = ['a','b','c','a','b']print(a.index('a',1,4))# 可以查找指定下标范围的元素,并返回找到对应数据的下标,输出:3print(a.index('a',1,3))# 范围区间,左闭右开,此代码会报错print(a.count('b'))# 统计某个元素出现几次,输出:2

6.排序和反转

a = [1,4,2,3]a.reverse()# 将列表所有元素反转print(a)# 输出:[3, 2, 4, 1]a.sort() # 直接升序排序a.sort(reverse=True) # 直接降序排列print(a)# 输出:[4, 3, 2, 1]

7.嵌套

例1:

schoolnames = [[],[],[]] # 有三个元素的空列表,每个元素都是一个空列表schoolname = [['北京大学','清华大学','中国人民大学'],['南开大学','天津大学'],['山东大学']]print(schoolname[0][0])# 类似于二维数组,输出:北京大学

例2:

import randomoffices = [[],[],[]]names = ['a','b','c','d','e','f','g']for name in names:index = random.randint(0,2)offices[index].append(name)i = 1for office in offices:print('办公室%d的人数为:%d'%(i,len(office)))i += 1for name in office:print('%s'%name,end='\t')print('\n')print('-'*20)''' 输出结果:办公室1的人数为:1f--------------------办公室2的人数为:1c--------------------办公室3的人数为:5a b d e g--------------------'''

二、元组

1.元组知识

tuple 与 list 类似,不同之处在于tuple的元素不能修改。tuple写在小括号里,元素之间用逗号隔开。元组的元素不变,但可以包含可变对象,如list。注意:定义一个只有1个元素的tuple,必须加逗号。

元组的定义与访问:

# 1 定义tup1 = () # 创建空的元组 <class 'tuple'>tup2 = (50)# <class 'int'>tup3 = (50,) # <class 'tuple'>tup4 = (50,60,70) # <class 'tuple'># 2 访问tup1 = ('abc','def',2000,)print(tup1[0])print(tup1[-1])# 访问最后一个print(tup1[1:3]) # 从下标为1到下标为3,左闭右开

2.增、删、改、查

# 3 增(连接)tup1 = (12,34,56)tup2 = ('abc','xyz')tup = tup1 + tup2print(tup)# 输出:(12, 34, 56, 'abc', 'xyz')# 4 删tup1 = (12,34,56)del tup1 # 删除整个元组变量# 5 改tup1 = (12,34,56)tup1[0] = 100 # 报错,不能修改# 6 查(见 # 2 访问)

3.遍历元组(通过for循环)

tup1 = (12,34,56)for i in tup1:print(i)'''输出:123456'''

4.对元组的操作

元组成员关系,操作方法:in,举例:2 in list1得到重复元素数量,方法:count,举例:tup1.count(1)其他对象变成元组,方法:tuple(),把对象直接放到括号里面获取元组的最大最小值及长度,max(),min(),len()

三、字典

1.字典知识

字典是无需的对象集合,使用键-值(key-value)存储,具有极快的查找速度。键(key)必须使用不可变类型。同一个字典中,键(key)必须是唯一的。

字典的定义与访问:

# 1 定义info = {'name':'Alice','age':20}# 2 访问print(info['name'])print(info['age'])print(info['gender']) # 直接访问了不存在的键,会报错print(info.get('gender')) # 使用get方法,没有找到对应的键,默认返回:noneprint(info.get('gender','m')) # 没找到的时候,可以设定默认值,返回mprint(info.get('age',18)) # 找到了age,则默认值18不生效

2.增、删、改、查

# 3 增info = {'name':'Alice','age':20}newID = input('请输入新的学号:')info['id'] = newID# 4 删# 4.1 del# 4.1.1 删键值对info = {'name':'Alice','age':20}print('删除前:%s'%info['name'])del info['name'] print('删除后:%s'%info['name'])# 删除了指定键值对,再次访问会报错# 4.1.2 删字典info = {'name':'Alice','age':20}print('删除前:%s'%info)del info print('删除后:%s'%info)# 删除了整个info字典,再次访问会报错# 4.2 clear 清空info = {'name':'Alice','age':20}print('清空前:%s'%info['name'])# 清空前:Aliceinfo.clear() # 清空了字典里的所有元素print('清空后:%s'%info['name'])# 清空了访问name会报错print('清空后:%s'%info)# 清空后:{}# 5 改info = {'name':'Alice','age':20}info['age'] = 22print(info['age'])# 输出:22# 6 查info = {'id':'12345','name':'Alice','age':20}print(info.keys())# 得到所有的键,列表方式# 输出:dict_keys(['id', 'name', 'age'])print(info.values()) # 得到所有的值(列表)# 输出:dict_values(['12345', 'Alice', 20])print(info.items())# 得到所有的项(列表),每个键值对是一个元组# 输出:dict_items([('id', '12345'), ('name', 'Alice'), ('age', 20)])# 6.1 遍历所有的键for key in info.keys():print(key)'''输出:idnameage'''# 6.2 遍历所有的值for value in info.values():print(value)'''输出:12345Alice20'''# 6.3 遍历所有的键值对for key,value in info.items():print('key=%s,value=%s'%(key,value)) '''输出:key=id,value=12345key=name,value=Alicekey=age,value=20'''# 6.4 使用枚举函数,同时拿到列表中的下标和元素内容mylist = ['a','b','c','d']for i,x in enumerate(mylist):print(i,x)'''输出:0 a1 b2 c3 d'''

3.对字典的操作

获取字典长度,用len()获取最大(最小)的Key,用max(),min()其他类型对象转换成字典,用dict(),举例:dict([(1,2),(2,3)])字典元素的弹出,用pop,例如:dict1.pop(‘小李’)判断Key是否存在,用in,例如:‘key’ in dict1合并字典,用update,例如:dict1.update(dict2)把两个列表转为字典,用dict+zip方法,例如:dict(zip(list1,list2))把一个嵌套列表转为字典,用dict方法,例如:dict2 = dict([[‘key1’,‘value1’]])清除字典内的元素,用clear的方法,例如:dict1.clear()

四、集合

1.集合知识

set和dict类似,也是一组key的集合,但不储存value。由于key不能重复,所以,在set中,没有重复的key。set是无序的,重复元素在set中自动被过滤。set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集(&)、并集(|)、差集(-)等操作。

集合的定义:

s = set([1,2,3])print(s)# 输出{1,2,3}s = set([1,1,2,2,3,3])print(s) # 输出{1,2,3},不重复,集合可以当作去重的操作

2.对集合的操作

遍历:for i in set1: print (i)更新:set1.update(set2)向集合添加新元素:set1.add(5)移除集合中的元素:set1.remove(5)弹出元素:val = set1.pop()清除元素:set1.clear()删除集合:del set1

总结

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。