python列表有哪些常用方法?
列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。列表的数据项不需要具有相同的类型。
python列表常用的方法:
1、append()方法
append()方法用于在列表末尾添加新的对象。
append()方法语法:list.append(obj)
示例:
#!/usr/bin/python
aList=[123,'xyz','zara','abc'];
aList.append(2009);
print"UpdatedList:",aList;
以上实例输出结果如下:
UpdatedList:[123,'xyz','zara','abc',2009]
2、count()方法
count()方法用于统计某个元素在列表中出现的次数。
count()方法语法:list.count(obj)
示例:
#!/usr/bin/python
aList=[123,'xyz','zara','abc',123];
print"Countfor123:",aList.count(123);
print"Countforzara:",aList.count('zara');
以上实例输出结果如下:
Countfor123:2
Countforzara:1
3、extend()方法
extend()方法用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。
extend()方法语法:list.extend(seq)
示例:
#!/usr/bin/python
aList=[123,'xyz','zara','abc',123];
bList=[2009,'manni'];
aList.extend(bList)
print"ExtendedList:",aList;
以上实例输出结果如下:
ExtendedList:[123,'xyz','zara','abc',123,2009,'manni']
4、index()方法
index()方法用于从列表中找出某个值第一个匹配项的索引位置。
index()方法语法:list.index(x[,start[,end]])
参数:
x--查找的对象。
start--可选,查找的起始位置。
end--可选,查找的结束位置。
5、pop()方法
pop()方法用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
pop()方法语法:list.pop([index=-1])
参数:
obj--可选参数,要移除列表元素的索引值,不能超过列表总长度,默认为index=-1,删除最后一个列表值。
返回值:该方法返回从列表中移除的元素对象。
6、remove()方法
remove()方法用于移除列表中某个值的第一个匹配项。
语法
remove()方法语法:list.remove(obj)
参数
obj--列表中要移除的对象。
返回值:该方法没有返回值但是会移除列表中的某个值的第一个匹配项。
以上内容为大家介绍了python列表有哪些常用方法?希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






