list方法

查看list的方法

使用dir函数查看list都有哪些命令可以使用

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

list方法

append

>>> list.append.__doc__
'L.append(object) -- append object to end'

正如doc文件描述的append函数是用于附加对象到列表的末尾。

count

>>> list.count.__doc__
'L.count(value) -> integer -- return number of occurrences of value'

统计目标值在列表中出现的次数。

extend

 

>>> list.extend.__doc__
'L.extend(iterable) -- extend list by appending elements from the iterable'

 

在列表的末尾一次性追加另一个序列的多个值。

index

>>> list.index.__doc__
'L.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.'

返回目标值第一次出现位置,如果不存在则抛出错误。可以设置查找的开始和结束位置。

insert

>>> list.insert.__doc__
'L.insert(index, object) -- insert object before index'

在指定位置插入元素

pop

>>> list.pop.__doc__
'L.pop([index]) -> item -- remove and return item at index (default last).\nRaises IndexError if list is empty or index is out of range.'

移除列表中的一个元素(默认最后一个),并且返回该元素的值。

remove

>>> list.remove.__doc__
'L.remove(value) -- remove first occurrence of value.\nRaises ValueError if the value is not present.'

用于移除列表中某个值的一个匹配项。

reverse

>>> list.reverse.__doc__
'L.reverse() -- reverse *IN PLACE*'

将列表中的元素反向存放。

sort

>>> list.sort.__doc__
'L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\ncmp(x, y) -> -1, 0, 1'

用于在原位置对列表进行排序。

方法实例

>>> hello = list('hello')
>>> hello
['h', 'e', 'l', 'l', 'o']
>>> hello.append('four')
>>> hello
['h', 'e', 'l', 'l', 'o', 'four']
>>> hello.count('four')
1
>>> hello.index('four')
5
>>> b=[1,2,3]
>>> hello.extend(b)
>>> hello
['h', 'e', 'l', 'l', 'o', 'four', 1, 2, 3]
>>> hello.insert(0,'for')
>>> hello
['for', 'h', 'e', 'l', 'l', 'o', 'four', 1, 2, 3]
>>> hello.pop()
3
>>> hello.pop(0)
'for'
>>> hello.remove('four')
>>> hello
['h', 'e', 'l', 'l', 'o', 1, 2]
>>> hello.reverse()
>>> hello
[2, 1, 'o', 'l', 'l', 'e', 'h']
>>> hello.sort()
>>> hello
[1, 2, 'e', 'h', 'l', 'l', 'o']
View Code

 

posted @ 2014-08-10 00:44  剥糖纸吃糖  阅读(287)  评论(0)    收藏  举报