Python列表的常用方法

一、列表是什么?

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

列表中元素之间没有任何关系,列表也是自带下标的,默认从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 list
print list[2]
list[2]=2001
print list[2]
['python', 'hello', 1998, 2008]
1998
2001
3. 删除列表元素

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

list=['python','hello',1998, 2008]
print list
del 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=1
for x in [1,2,3]:      //迭代
    print x
4
[1, 2, 3, 4, 5, 6]
['hello!hello!hello!hello!']
True
1
2
3
5. 列表截取

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

函数:

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

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

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

print (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]






  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值