Python列表的常用方法

来源:互联网 发布:软件开发招聘广告 编辑:程序博客网 时间:2024/05/18 00:58

一、列表是什么?

列表是由一序列特定顺序排列的元素组成的,可以把字符串、数字、字典等都可以加入列表中。

列表中元素之间没有任何关系,列表也是自带下标的,默认从0开始。

列表是最常用的Python数据类型,可以作为一个方括号内的逗号分隔值出现。

列表的数据项不需要具有相同的类型。

1. 创建列表

只需要把头号分隔的不同的数据项使用方括号括起来即可。如:

list1=['python','abc',1000]list2=[1,2,3,4,5]list3=["a","b"]
与字符串的索引一样,列表索引从0开始,列表可以进行各种操作,比如:append、index、insert、pop、remove、sort、reverse、切片等

2. 访问列表

使用下标索引来访问列表中的值,也可以使用方括号的形式获取字符。

list1=['python','abc',1000]list2=[1,2,3,4,5]list3=["a","b"]print list1[0]print list2[1:5],list2[1:5:2]

python[2, 3, 4, 5] [2, 4]
2. 更新列表

对列表中的数据进行修改或者更新

list=['python','hello',1998, 2008]print listprint list[2]list[2]=2001print list[2]
['python', 'hello', 1998, 2008]19982001
3. 删除列表元素

可以使用del语句删除列表的元素:

list=['python','hello',1998, 2008]print listdel list[2]print list
['python', 'hello', 1998, 2008]['python', 'hello', 2008]
4. 列表脚本操作符

列表对+ 和*的操作符与字符串类似,+ 用于组合列表,*用于重复列表

print len([1,2,3,4])   //求列表长度print [1,2,3]+[4,5,6]  //两个列表组合print ['hello!'*4]     // 列表重
print 3 in [1,2,3]    // 判断元素是否存在
x=1for x in [1,2,3]:      //迭代    print x
4[1, 2, 3, 4, 5, 6]['hello!hello!hello!hello!']True123
5. 列表截取

list=['python','hello','yangyang']print list[2]  //取出第三个元素print list[-2]//取出倒数第二个元素print list[1:]//从第二个列表截取列表
yangyanghello['hello', 'yangyang']
6. 列表函数 与方法

函数:

序号函数1cmp(list1, list2) //比较两个列表的元素2len(list) //列表元素个数3max(list)//返回列表元素最大值4min(list)//返回列表元素最小值5list(seq)//将元组转换为列表

list1=['python','hello','yangyang']list2=['python',1,2,3]print cmp(list1,list2)print len(list1)print max(list2)
13python
方法: 

序号方法1list.append(obj)//在列表末尾添加新的对象2list.count(obj) //统计某个元素在列表中出现的次数3list.extend(seq) //在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)4list.index(obj) //从列表中找出某个值第一个匹配项的索引位置5list.insert(index, obj)//将对象插入列表6list.pop(obj=list[-1])// 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值7list.remove(obj)//移除列表中某个值的第一个匹配项8list.reverse()//反向列表中元素9list.sort([func])//对原列表进行排序

print["append"* 10]a=['python','hello','yangyang',1,2,3]print (a)a.append('ssss')print (a)print ['index'*10]print (a.index('yangyang'))print (a)a.pop()print aprint (a)a.sort()print (a)a.reverse()print (a)a.insert(3,'dddd')print (a)
['appendappendappendappendappendappendappendappendappendappend']['python', 'hello', 'yangyang', 1, 2, 3]['python', 'hello', 'yangyang', 1, 2, 3, 'ssss']['indexindexindexindexindexindexindexindexindexindex']2['python', 'hello', 'yangyang', 1, 2, 3, 'ssss']['python', 'hello', 'yangyang', 1, 2, 3]['python', 'hello', 'yangyang', 1, 2, 3][1, 2, 3, 'hello', 'python', 'yangyang']['yangyang', 'python', 'hello', 3, 2, 1]['yangyang', 'python', 'hello', 'dddd', 3, 2, 1]