列表的其他使用方法

dir(list)可以查看列表包含的方法:

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

红色的是列表的所有包含的方法。

count():用于统计列表中某个元素出现的次数

index():用于判断某个元素在列表中出现的位置

pop():用于将列表当成栈使用,实现元素出栈功能。

reverse():用于将列表中的元素反向存放

sort():用于对列表元素排序

>>> a=list('abab13421')
>>> a
['a', 'b', 'a', 'b', '1', '3', '4', '2', '1']
>>> a.count('a')
2
>>> a.index('4')
6
>>> a.pop()
'1'
>>> a
['a', 'b', 'a', 'b', '1', '3', '4', '2']
>>> a.reverse()
>>> a
['2', '4', '3', '1', 'b', 'a', 'b', 'a']
>>> a.sort()
>>> a
['1', '2', '3', '4', 'a', 'a', 'b', 'b']

>>> a.index('4',2)#可以指定开始的位置查找
3
>>> a.index('2',3)
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
a.index('2',3)
ValueError: '2' is not in list

>>> b=['go','good','dog','school','list','a','ptthon','b']
>>> b.sort(key=len)
>>> b
['a', 'b', 'go', 'dog', 'good', 'list', 'school', 'ptthon']
>>> b.sort(key=len,reverse=True)
>>> b
['school', 'ptthon', 'good', 'list', 'dog', 'go', 'a', 'b']

原文地址:https://www.cnblogs.com/inuyashalove/p/12736244.html