Python基础 列表

时间:2023-03-09 02:20:44
Python基础 列表

---***---传送门---***---

文档解释

def append(self, p_object):
    """ L.append(object) -> None -- append object to end """
    pass

def clear(self):
    """ L.clear() -> None -- remove all items from L """
    pass

def 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 0

def extend(self, iterable):
    """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
    pass

def 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 0

def insert(self, index, p_object):
    """ L.insert(index, object) -- insert object before index """
    pass

def 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.
    """
    pass

def remove(self, value): _
    """
    L.remove(value) -> None -- remove first occurrence of value.
    Raises ValueError if the value is not present.
    """
    pass

def reverse(self):
    """ L.reverse() -- reverse *IN PLACE* """
    pass

def sort(self, key=None, reverse=False):
    """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
    pass

[] == [None:None]

切片

+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
  0   1   2   3   4   5
 -6  -5  -4  -3  -2  -1
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