首页 > 代码库 > Python基础 列表

Python基础 列表

文档解释

def append(self, p_object):    """ L.append(object) -> None -- append object to end """    passdef clear(self):     """ L.clear() -> None -- remove all items from L """    passdef copy(self):     """ L.copy() -> list -- a shallow copy of L """    return []def count(self, value):     """ L.count(value) -> integer -- return number of occurrences of value """    return 0def extend(self, iterable):    """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """    passdef index(self, value, start=None, stop=None):     """    L.index(value, [start, [stop]]) -> integer -- return first index of value.    Raises ValueError if the value is not present.    """    return 0def insert(self, index, p_object):    """ L.insert(index, object) -- insert object before index """    passdef pop(self, index=None):     """    L.pop([index]) -> item -- remove and return item at index (default last).    Raises IndexError if list is empty or index is out of range.    """    passdef remove(self, value): _    """    L.remove(value) -> None -- remove first occurrence of value.    Raises ValueError if the value is not present.    """    passdef reverse(self):    """ L.reverse() -- reverse *IN PLACE* """    passdef sort(self, key=None, reverse=False):    """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """    pass

[] == [None:None] 

切片

li = [‘a‘, ‘b‘, ‘c‘, ‘d‘]print(li)print(li[1:3])print(li[:4])print(li[3:])print(li[::2])print(li[1::-1])  # 步长-1表示反向取值,print(li[1:-1])
[‘a‘, ‘b‘, ‘c‘, ‘d‘][‘b‘, ‘c‘][‘a‘, ‘b‘, ‘c‘, ‘d‘][‘d‘][‘a‘, ‘c‘][‘b‘, ‘a‘][‘b‘, ‘c‘]

追加 append(在尾部添加)


强行插入 insert (在指定位置添加)

 

li = [‘a‘, ‘b‘, ‘c‘, ‘d‘]print(li)li.append(‘e‘)print(li)li.insert(1, ‘g‘)print(li)
[‘a‘, ‘b‘, ‘c‘, ‘d‘][‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘][‘a‘, ‘g‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]

删除(remove, pop, del)

remove() 删除单个元素

li = [‘a‘, ‘b‘, ‘c‘, ‘d‘]li.remove(‘a‘)print(li)

pop() 默认删除最后一个,也可指定引索删除。有返回值!

li = [‘a‘, ‘b‘, ‘c‘, ‘d‘]b = li.pop(2)print(li)print(b)
[‘a‘, ‘b‘, ‘d‘]c

del

li = [‘a‘, ‘b‘, ‘c‘, ‘d‘]del li[2]print(li)li = [‘a‘, ‘b‘, ‘c‘, ‘d‘]del li[:2]print(li)
[‘a‘, ‘b‘, ‘d‘][‘c‘, ‘d‘]

count 统计指定元素在列表出现的次数

li = [‘a‘, ‘a‘, ‘a‘, ‘b‘, ‘c‘, ‘d‘]n = li.count(‘a‘)print(n)
3

  

  

 

 

Python基础 列表