python列表常用函数_python中常用的列表类型内建函数

1、list.append(obj) 向列表中添加一个对象obj

list = [‘apple‘, ‘pear‘, ‘orange‘]

>>> list.append(‘apple‘)

>>> list

[‘apple‘, ‘pear‘, ‘orange‘, ‘apple‘]

2、list.count(obj) 返回一个对象obj在列表中出现的次数

>>> list.count(‘apple‘)

2

3、list.extend(seq) 把序列seq的内容添加到列表中

>>> seq = [‘banana‘, ‘strawberry‘]

>>> list.extend(seq)

>>> list

[‘apple‘, ‘pear‘, ‘orange‘, ‘apple‘, ‘banana‘, ‘strawberry‘]

4、list.index(obj, i=0, j=len(list))

返回 list[k] == obj 的 k 值,并且 k 的范围在 i<=k

>>> list.index(‘orange‘,0, len(list))

2

>>> list.index(‘lemon‘,0, len(list))

Traceback (most recent call last):

File "", line 1, in

list.index(‘lemon‘,0, len(list))

ValueError: ‘lemon‘ is not in list

5、list.insert(index, obj) 在索引量为 index 的位置插入对象obj

>>> list.insert(3, ‘lemon‘)

>>> list

[‘apple‘, ‘pear‘, ‘orange‘, ‘lemon‘, ‘apple‘, ‘banana‘, ‘strawberry‘]

6、list.pop(index=-1) 删除并返回指定位置的对象,默认是最后一个对象

>>> list.pop()

‘strawberry‘

>>> list

[‘apple‘, ‘pear‘, ‘orange‘, ‘lemon‘, ‘apple‘, ‘banana‘]

7、list.remove(obj) 从列表中删除找到的第一个obj对象,如果不存在则返回一个ValueError错误。

>>> list.remove(‘apple‘)

>>> list

[‘pear‘, ‘orange‘, ‘lemon‘, ‘apple‘, ‘banana‘]

>>> list.remove(‘strawberry‘)

Traceback (most recent call last):

File "", line 1, in

list.remove(‘strawberry‘)

ValueError: list.remove(x): x not in list

8、list.reverse() 原地翻转列表

>>> list.reverse()

>>> list

[‘banana‘, ‘apple‘, ‘lemon‘, ‘orange‘, ‘pear‘]

9、list.sort(func=None,key=None,

reverse=False) 以指定的方式排序列表中的成员,如果 func 和 key 参数指定,则按照指定的方式比较各个元素,如果 reverse 标志被置为True,则列表以反序排列。

>>> list.sort()

>>> list

[‘apple‘, ‘banana‘, ‘lemon‘, ‘orange‘, ‘pear‘]

>>> list.sort(reverse=True)

>>> list

[‘pear‘, ‘orange‘, ‘lemon‘, ‘banana‘, ‘apple‘]

原文:http://blog.csdn.net/xc_tsao/article/details/25462053

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值