您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

盘点Python基础之列表的那些事儿

2024/4/14 3:35:32发布19次查看
一、列表的格式示例:
nameslist = ['xiaowang','xiaozhg','xiaa']
比c语言的数组强大的地方在于列表中的元素可以是不同类型的。
testlist = [1, 'a']
二、列表的相关操作("增"、"删"、"改",“查”)
<1> 添加元素
append()通过append可以向列表添加元素。
例:
# 定义变量a,默认有3个元素a = ['rr', 'rag', 'rte']print("-----添加之前,列表a的数据-----")for tempname in a: print(tempname)# 提示、并添加元素temp = input('请输入要添加的学生姓名:')a.append(temp)print("-----添加之后,列表a的数据-----")for tempname in a: print(tempname)
运行结果:
<2> 修改元素("改")
修改元素的时候,要通过下标来确定要修改的是哪个元素,然后才能进行修改。
例:
# 定义变量a,默认有3个元素a = ['rr', 'rag', 'rte']print("-----修改之前,列表a的数据-----")for tempname in a: print(tempname)# 修改元素a[1] = 'lu'print("-----修改之后,列表a的数据-----")for tempname in a: print(tempname)
结果:
<3> 查找元素("查"in, not in, index, count)
python中查找的常用方法为:
in(存在),如果存在那么结果为true,否则为false。
not in(不存在),如果不存在那么结果为true,否则false。



#待查找的列表 a = ['rr', 'rag', 'rte'] #获取用户要查找的名字 findname = input('请输入要查找的内容:') #查找是否存在 if findname in a: print('在字典中找到了相同的内容') else: print('没有找到')
运行结果:(找到)
运行结果:(没有找到)
注:
in的方法只要会用了,那么not in也是同样的用法,只不过not in判断的是不存在。
<4> 删除元素("删"del, pop, remove)
del (根据下标进行删除)



name = ['加勒比海盗','骇客帝国','第一滴血','霍比特人','速度与激情']print('------删除之前------')for tempname in name: print(tempname)del name[2]print('------删除之后------')for tempname in name: print(tempname)
结果:
pop(删除最后一个元素)
subject= ['数学', '语文', '英语', '地理', '历史']print('------删除之前------')for tempsubject in subject: print(tempsubject)del subject[2] #删除第二个元素print('------删除之后------')for tempsubject in subject: print(tempsubject)
运行结果:
remove (根据元素的值进行删除)



subject= ['数学', '语文', '英语', '地理', '历史']print('------删除之前------')for tempsubject in subject: print(tempsubject)# del subject[2] #删除第二个元素subject.remove('英语')print('------删除之后------')for tempsubject in subject: print(tempsubject)
结果:
<5> 排序(sort, reverse)
sort方法是将list按特定顺序重新排列,默认为由小到大,参数reverse=true可改为倒序,由大到小。
reverse方法是将list逆置。
a = [1, 4, 2, 3]print(a)a.reverse()print(a) # 运行结果a.sort()print(a) # 运行结果a.sort(reverse=true)print(a) # 运行结果
运行结果:
三、列表的嵌套
1. 列表嵌套类似while循环的嵌套,列表也是支持嵌套的。
一个列表中的元素又是一个列表,那么这就是列表的嵌套。
例:
letter= [['a', 'b'], ['c', 'd', 'e'], ['f', 'r']]
2. 字典列表
列表中包含字典。比如花名册:
pep1 = {'name': '蔡同学', 'school': '北京大学'}pep2 = {'name': '陈作同', 'school': '中山大学'}pep_list = [pep1, pep2]for pepo in pep_list: print(pepo)
运行结果:
有的应用场景,会在列表中包含大量的字典, 而且其中的每个字典都会包含拥有众多属性的大对象。
3. 列表字典字典包含列表。比如图书的标签,一本书会被标注多个标签:
book = {'title': '现代艺术150年', 'tags': ['数学', '历史学']}for tags in book['tags']: print(tags)
运行结果:
四、总结    本文详细的讲解了python基础 。介绍了常见的列表操作,以及在实际操作中会遇到的问题,提供了解决方案。最后通过一个小项目,使读者能够更好的理解python列表的使用方法。希望可以帮助你更好的学习。
以上就是盘点python基础之列表的那些事儿的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product