当前位置: 首页 > 科技观察

通用Python的秘密:用于操作数据的内置工具

时间:2023-03-19 00:59:34 科技观察

Python可以说是当今最流行的编程语言,甚至孩子们也可以通过它开始学习有趣的编程。Python简单的类似英语的语法使其成为一种通用语言,广泛应用于世界各地的各个领域。Python的多功能性在于其内置的数据结构,这使得编码变得容易,独立于数据类型,并根据需要操作数据。首先,让我们试着理解什么是数据结构?数据结构是一种结构/容器,能够存储、组织和管理数据,以便可以有效地访问和使用数据。数据结构是数据类型的集合。Python中有四种内置数据结构。它们是:列表字典元组集合开发人员使用的最常见的数据结构是列表和字典。接下来,让我们详细看看每个数据结构。1.列表Python列表是按顺序排列的任何类型的项目的集合。列表可以有重复的项目,因为每个项目都使用索引访问,而列项目可以使用负索引反向访问。列表是可变的,这意味着即使在创建项目之后也可以添加、删除或更改项目;一个列表也可以包含另一个列表。(1)创建列表:可以通过将元素括在[]方括号中来创建列表,每一项用逗号分隔。以购物清单为例,创建清单的语法为:#Creatingalistfruits=['Apple','Banana',"Orange"]print(type(fruits))#returnstypeprint(fruits)#printstheelementsofthelistOutput:['Apple','Banana','Orange'](2)访问列表:可以使用索引访问列表中的项目。列表中的每个项目都有一个与之关联的索引,具体取决于项目在列表中的位置。访问列表中项目的语法:#Accesselementsinthefruitslistfruits=['Apple','Banana',"Orange"]print(fruits[0])#index0isthefirstelementprint(fruits[1])print(fruits[2])Output:AppleBananaOrangeBut,该指数不必总是正数。如果要反向访问列表,即倒序访问,可以使用负索引,如下:#Accesselementsinthefruitslistusingnegativeindexesfruits=['Apple','Banana',"Orange"]print(fruits[-1])#index-1isthelastelementprint(fruits[-2])print(fruits[-3])Output:OrangeBananaApple如果必须返回列表中两个位置之间的元素,请使用切片。必须指定开始和结束索引才能从列表中获取一定范围的元素。语法是List_name[start:end:step]。这里的步长是增量值,默认为1。#Accessingrangeofelementsusingslicingfruits=['Apple','Banana',"Orange"]fruits#allelements['Apple','Guava','Banana','Kiwi']#outputfruits[::1]#starttoendwithstep1['Apple','番石榴','香蕉','奇异果']#outputfruits[::2]#starttoendwithstep2basicallyindex0&2['Apple','香蕉']#outputfruits[::3]#starttoendwithstep2basicallyindex0&3['Apple','奇异果']#outputfruits[::-1]#starttoendwithstep2-reverseorder['Kiwi','Banana','Guava','Apple']#output(3)向列表添加元素:可以使用append()、extend()和insert()函数将一个项目添加到列表中。#Addingelementsfruits=['Apple','Banana',"Orange"]#Appendnewelementsfruits.append('Kiwi')print(fruits)输出:['Apple','Banana','Orange','Kiwi']#Insertelementsintothelistfruits.insert(1,'Guava')#insertsGuavaassecondelementisthelistsincetheindexisspecifiedas1print(fruits)Output:['Apple','Guava','Banana','Orange','Kiwi'](4)从列表中移除项目:类似于添加元素,从列表中删除元素也非常容易,使用del()、remove()和pop()方法即可实现。要清除整个列表,您可以使用clear()函数。del()函数删除给定索引处的元素。pop()函数从列表中删除给定索引处的元素,还可以将删除的元素分配给变量。如果未指定索引值,则删除列表中的最后一个元素。remove()函数根据元素的值删除元素。clear()函数清除列表。#Deletingelementsfromthelistfruits=['Apple','Guava','Banana','Orange','Kiwi']#del()functiondelfruits[3]#deleteelementatindex4print(fruits)输出:['Apple','番石榴','香蕉','Kiwi']#pop()functiondel_fruit=fruits.pop(2)print(del_fruit)print(fruits)输出:'Banana'['Apple','Guava','Orange','Kiwi']#Removefunctionfruits.remove('Apple')print(fruits)Output:['Guava','Banana','Orange','Kiwi']#Clear()functionfruits.clear()print(fruits)Output:[]#clearsthelist其他函数:在处理列表时,可以使用其他几个函数:len()函数返回列表的长度。index()函数查找第一个遇到的值的索引值。count()函数查找传递给它的值的数量。sorted()和sort()函数用于对列表的值进行排序。sorted()有返回类型,而sort()修改原始列表。#Otherfunctionsforlistnum_list=[1,2,3,10,20,10]print(len(num_list))#findlengthoflistprint(num_list.index(10))#findindexofelementthatoccursfirstprint(num_list.count(10))#findcountoftheelementprint(sorted(num_list))#printsortedlistbutnotchangeoriginalnum_list.sort(reverse=True)#sortoriginallistprint(num_list)Output:632[1,2,3,10,10,20][20,10,10,3,2,1]2.Dictionary字典是另一个一种无序数据结构,其中元素的存储顺序与其插入顺序不同。这是因为索引值无法访问字典中的元素。在字典中,数据以键值对的形式存储,通过键访问元素值。图源:unsplash(1)创建字典:字典是通过逗号分隔的{}大括号或者使用dict()函数写入键和值来创建的。#CreatingDictionariesnew_dict={}#emptydictionaryprint(new_dict)new_dict={1:'Python',2:'Java'}#dictionarywithelementsprint(new_dict)输出:{}{1:'Python',2:'Java'}(2)改变和增加键值对:要改变字典的值,使用键访问键,然后相应地改变值。要添加一个值,只需添加另一个键值对,如下所示:#ChangingandAddingkey,valuepairslang_dict={'First':'Python','Second':'Java'}print(lang_dict)lang_dict['Second']='C++'#changingelementprint(lang_dict)lang_dict['Third']='Ruby'#addingkey-valuepairprint(lang_dict)Output:{'First':'Python','Second':'Java'}{'First':'Python','Second':'C++'}{'First':'Python','Second':'C++','Third':'Ruby'}(3)访问字典中的元素:字典中的元素可以只能使用键访问,您可以使用get()函数或仅通过键获取值。#AccessingElementslang_dict={'First':'Python','Second':'Java'}print(lang_dict['First'])#accesselementsusingkeysprint(lang_dict.get('Second'))Output:PythonJava(4)删除字典的键值对:这些是字典中用于删除元素的函数。pop()-删除一个值并返回删除的值popitem()-接受一个键值对并返回一个键和值的元组clear()-清除整个字典#Deletingkey,valuepairsinadictionarylang_dict={'First':'Python','Second':'Java','Third':'Ruby'}a=lang_dict.pop('Third')#popelementprint('Value:',a)print('Dictionary:',lang_dict)b=lang_dict.popitem()#popthekey-valuepairprint('Key,valuepair:',b)print('Dictionary',lang_dict)lang_dict.clear()#emptydictionaryprint(lang_dict)Output:Value:Ruby#popelementDictionary:{'First':'Python','Second':'Java'}Key,valuepair:('Second','Java')#popthekey-valuepairDictionary{'First':'Python'}{}#emptydictionary(5)其他函数:下面是一些其他可以与函数一起使用的函数与字典一起使用以获取键值和键值对等。#Otherfunctionsfordictionarylang_dict={'First':'Python','Second':'Java','Third':'Ruby'}print(lang_dict.keys())#getkeysprint(lang_dict.values())#getvaluesprint(lang_dict.items())#getkey-valuepairsprint(lang_dict.get('First'))输出:dict_keys(['First','Second','Third'])dict_values(['Python','Java','Ruby'])dict_items([('First','Python'),('Second','Java'),('Third','Ruby')])Python3.tuplemap来源:unsplashtuples基本上和lists一样,不同的是一旦数据在tuple中,就不能再以任何方式改变。因此,元组一旦生成,就不能添加、删除或编辑任何值。(1)创建元组:使用()括号或tuple()函数创建元组。#CreatingTuplesmy_tuple=(1,2,3)#createtupleprint(my_tuple)输出:(1,2,3)#CreatingTuplesmy_tuple=(1,2,3)#createtupleprint(my_tuple)输出:(1,2,3)(2)访问元组中的元素:访问元组元素类似于列表。#accesselementsmy_tuple2=(1,2,3,'new')forxinmy_tuple2:print(x)#printsalltheelementsinmy_tuple2print(my_tuple2)print(my_tuple2[0])#1stelementprint(my_tuple2[:])#allelementsprint(my_tuple2[3][1])#thisreturnsthe2ndcharacteroftheelementatindex3print(my_tuple2[-1])#lastelementOutput:123new(1,2,3,'new')1(1,2,3,'new')enew(3)在另一个元组中追加元素:要追加值,您可以使用“+”运算符。#Appendingelementsmy_tuple=(1,2,3)my_tuplemy_tuple=my_tuple+(4,5,6)#addelementsprint(my_tuple)Output:(1,2,3,4,5,6)(4)元组赋值:元组打包有用的解包和解包操作,将另一个元组的元素分配给一行中的当前元组。元组打包是通过添加单个值来创建元组,而元组拆包是将元组中的值赋值给变量。#tuplepackingplanets=('地球','火星','木星')#tupleunpackinga,b,c=planetsprint(a)print(b)print(c)输出:EarthMarsJupiter4。集合图源:unsplash集合是唯一无序的A集合元素。这意味着即使数据重复多次,集合也只保留一次。(1)创建集合:使用{}花括号创建集合并赋值。#Creatingsetsnew_set={1,2,3,4,4,4,5}#createsetprint(new_set)输出:{1,2,3,4,5}(2)向集合中添加元素:使用add()函数分配和添加元素。#AddingelementstoaSetnew_set={1,2,3}new_set.add(4)#addelementtosetprint(new_set)输出:{1,2,3,4}(3)集合操作:可以对集合执行的不同操作如下如下。union()函数组合来自两个集合的数据。intersection()函数仅查找同时出现在两个集合中的数据。difference()函数删除存在于两个集合中的数据,并仅输出存在于传递的集合中的数据。symmetric_difference()函数执行与difference()函数相同的操作,但输出两个集合中保存的数据。clear()函数清除集合。#Operationsonsetmy_set={1,2,3,4}my_set_2={3,4,5,6}print(my_set.union(my_set_2))print(my_set.intersection(my_set_2))print(my_set.difference(my_set_2))打印(my_set.symmetric_difference(my_set_2))my_set.clear()打印(my_set)输出:{1,2,3,4,5,6}{3,4}{1,2}{1,2,5,6}set()Python为我们提供了多种有效管理、组织和访问数据的选项。学习其基本的内置数据结构是Python学习之旅中非常关键的一部分。