当前位置: 首页 > 后端技术 > PHP

PHPer谈Python的数据结构

时间:2023-03-29 16:09:51 PHP

背景最近在学习Python。本文主要记录学习Python时关于数据结构的一些心得。数据结构list#listdemoshopList=['apple','mango','carrot','banana']#len()计算list长度print(len(shopList))#遍历listforiteminshopList:print(item,end='')#添加元素shopList.append('rice')print('Myshoppinglistisnow',shopList)#SortshopList.sort()print('Myshoppinglistisnow',shopList)#删除元素delshopList[0]print('Myshoppinglistisnow',shopList)#向列表中插入元素shopList.insert(1,'red')print('Myshoppinglistisnow',shopList)#从列表末尾删除元素shopList.pop()print('Myshoppinglistisnow',shopList)Python中的列表类似于PHP中的数值数组元组#tupledemozoo=('python','elephant','penguin')#len()计算长度print(len(zoo))#访问元组中的值print(zoo[1])元组和列表很相似,但是之后不能修改值元组被初始化。Dictionary#demoabofdictionary={'Swaroop':'swaroop@swaroopch.com','Larry':'larry@wall.org','Matsumoto':'matz@ruby-lang.org','Spammer':'spammer@hotmail.com'}#访问字典中的元素print(ab['Swaroop'])print(ab.get('Swaroop'))#assignab['test']='test'print(ab)#删除元素ab.pop('Larry')print(ab)delab['Spammer']print(ab)#遍历ab.items()中的名称、地址字典:print('Contact{}at{}'.format(name,address))Python中的字典类似于PHP的关联数组collection#collectiondemobri=set(['bra','rus','ind'])#newelementbri.add('test')print(bri)#移除元素bri.remove('rus')print(bri)#判断元素是否存在于集合中print('bra'inbri)总结了Python中四大数据结构的简单用法。如有错误,请指正。趁着疫情期间,多多了解~文章首发地址:https://tsmliyun.github.io/py...