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

Python基础知识列表介绍

时间:2023-03-26 15:20:43 Python

1.什么是列表?1.1访问列表元素使用索引来访问元素。bicycles=['trek','cannondale','redline','specialized']print(bicycles[0])1.2索引从0开始和其他语言一样,列表从0开始。Python提供了索引值-1,它返回列表的最后一个元素。2.修改、添加和删除元素2.1修改列表元素指定要修改的元素的列表和索引,然后指定元素的新值。motorcycles=['honda','yamaha','suzuki']print(motorcycles)motorcycles[0]='ducati'print(motorcycles)#第一个位置的值指定为新值,起到了作用修改2.2向列表添加元素①在列表末尾添加元素append()方法,在末尾添加元素。②在列表中插入元素insert()方法,在列表任意位置添加一个新元素,需要指定索引和值。Variable.insert(indexvalue,newelement)2.3从列表中删除元素从列表中删除一个或多个元素。①使用del语句删除元素如果知道要删除的元素在列表中的位置,就可以使用del语句。motorcycles=['honda','yamaha','suzuki']print(motorcycles)#删除第一个元素delmotorcycles[0]print(motorcycles)②使用pop()方法删除列表中的元素,并继续使用这个值,使用pop()方法。pop()是弹出列表末尾的元素。motorcycles=['honda','yamaha','suzuki']poped_motorcyles=motorcycles.pop()print(motorcycles)print(poped_motorcyles)输出结果为:['honda','yamaha']suzuki③在任意位置弹出元素使用pop()方法在任意位置弹出一个元素,需要在括号中加上指定的索引。motorcycles=['honda','yamaha','suzuki']first_owned=motorcycles.pop(0)print(motorcycles)print('我拥有的第一辆摩托车是'+first_owned.title()+'.')#第一个弹出位置的值输出是:['yamaha','suzuki']我拥有的第一辆摩托车是本田。注意:如果你不确定是用del还是pop(),判断标准是if要从列表中删除一个元素,并且不以任何方式使用它,使用del语句;如果要在删除元素后继续使用它,请使用pop()方法。④根据值删除元素如果不知道要删除的元素在列表中的位置,但知道元素的值,可以使用remove()。motorcycles=['honda','yamaha','suzuki','ducati']too_expensive='ducati'motorcycles.remove(too_expensive)print(motorcycles)print('\nA'+too_expensive.title()+'太贵了expensiveforme.')Theoutputresultis:['honda','yamaha','suzuki']杜卡迪对我来说太贵了。注意:remove()方法只能删除第一个指定的值,如果要删除的值在列表中出现多次,需要循环语句删除所有值。3.组织列表中元素的排序是不可预测的。如果需要调整排序顺序,使用如下方法3.1使用方法sort()方法对列表进行永久排序按字母顺序排序sort()按字母倒序排序sort(reverse=True)cars=['bmw','audi','toyota','subaru']print(cars)cars.sort()print(cars)cars.sort(reverse=True)print(str(cars).title())输出:['bmw','audi','toyota','subaru']['audi','bmw','subaru','toyota']['Toyota','Subaru','Bmw','Audi']3.2调用函数sorted()暂时对列表排序Sortalphabeticallysorted()Reversealphabeticalsortsorted(reverse=True)cars=['bmw','audi','toyota','subaru']print(cars)print(sorted(cars))print(cars)print(sorted(cars,reverse=True))print(cars)输出:['bmw','audi','toyota','subaru']['audi','bmw','subaru','丰田']['宝马','奥迪','丰田','斯巴鲁']['丰田','斯巴鲁','宝马','奥迪']['宝马','奥迪','丰田','subaru']3.3向后打印列表方法reverses()可用于反转列表元素的顺序。cars=['bmw','audi','toyota','subaru']cars.reverse()print(cars)输出:['subaru','toyota','audi','bmw']3.4确定列表长度使用函数len()可以快速获取列表的长度。Python从1开始计算列表的长度,有几个元素,长度就是个数。cars=['bmw','audi','toyota','subaru']length=len(cars)print(length)输出:43.5使用列表避免索引错误索引-1总是返回最后一个列表元素,所以无论列表内容如何变化,index-1是最后一个元素。(当列表不包含任何元素时会报错)