Python list - zhongjiajie/zhongjiajie.github.com GitHub Wiki

Python-list

创建

  • list方法创建: list("JQKA")通过list方法创建出["J","Q","K","A"]列表

  • 列表解析创建: [str(n) for n in range(2, 11)]创建["2","3","4","5","6","7","8","9","10"]

  • 创建嵌套的list: 正确的创建方式应该是l = [['_'] * 3 for i in range(3)],此时的标记才是正确的,如l[1][2]='X';l的值是[['_', '_', '_'], ['_', '_', 'X'], ['_', '_', '_']].如果使用l = [['_'] * 3] * 3初始值可以得到与前一种方式类似的结果,但是其实际情况是创建了指向['_', '_', '_']的三个引用,更新值的时候会有所不同l[1][2]='X',此时的l值是[['_', '_', 'X'], ['_', '_', 'X'], ['_', '_', 'X']]

    # 方法一类似, 每次生成一个新对象 append 到 l 中
    l = []
    for i in range(3):
        row=['_'] * 3
        l.append(row)
    
    # 方法二类似, 追加同一个对象 row 到 l中去
    row = ['_'] * 3
    l = []
    for i in range(3):
        l.append(row)

del操作

可以删除列表中的元素或者切片,与pop相比没有返回被删除的元素,也可以对切片进行删除

  • 删除单个元素: l = list(range(5)); l; del l[0]; l
  • 删除列表的切片: l = list(range(5)); l; del l[0:2]; l

基本的方法

Data Structures

  • 其中append extend insert remove clear sort reverse只是修改了列表的值但是没有返回值(他们的返回值默认为None)
  • append: list.append(x)Add an item to the end of the list. Equivalent to a[len(a):] = [x]
  • extend: list.extend(iterable)Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable
  • insert: list.insert(i, x)Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x)
  • remove: list.remove(x)Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item
  • pop: list.pop([i])Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
  • clear: list.clear()Remove all items from the list. Equivalent to del a[:]
  • index: list.index(x[, start[, end]])Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item
    • The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument
  • count: list.count(x)Return the number of times x appears in the list
  • sort: list.sort(key=None, reverse=False)Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation)
  • reverse: list.reverse()Reverse the elements of the list in place
  • copy: list.copy()Return a shallow copy of the list. Equivalent to a[:]
  • count: list.count(item)item的数量

list元素拼接

  • 列表通过符号拼接成字符串
# 1
a = ["1", "2", "3", "test", "tmp"]
"/".join(a)
a = [1, 2, 3, "test", "tmp"]  # 如果有元素非str类型
"/".join(map(str, a)) # 或者用 列表解析 "/".join(str(i) for i in a)
)
# 2
from str import join  #  更加容易理解的版本
sentence = ['this','is','a','sentence']
join(sentence, "-")
# 3
import os
os.path.join(*map(str, a)  # 只能时路径分隔符,但是会自动合并多余的 "/" 符号
  • 两个列表拼接
    • 直接用+号: [str(n) for n in range(2, 11)] + list('JQKA')

List Comprehensions

要了解列表解析的逻辑过程,这样才能写出正确的代码,其解析的原则是:如果只有一个中括号会按照for和if的顺序解析,最后计算列表元素的值(看下面递进解析列表解析数据);如果有多个中括号会先从外到内解析括号的表达式(看下面的嵌套列表),列表推导也可能被滥用,通常的原则是,只用列表推导来创建新的列表,并且尽量保持简短。

  • 简单的列表解析: [x**2 for x in range(10)]得到的是0-9的平方列表,相当于for x in range(10): x**2

  • 复杂点的列表解析: [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]拥有多个for或者if的列表解析,相当于

    combs = []
    for x in [1,2,3]:
        for y in [3,1,4]:
            if x != y:
                combs.append((x, y))
  • 递进处理列表解析数据: vec = [[1,2,3], [4,5,6], [7,8,9]];[num for elem in vec for num in elem];得到的是[1, 2, 3, 4, 5, 6, 7, 8, 9]

  • 嵌套列表

    matrix = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]
    [[row[i] for row in matrix] for i in range(4)]
    # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
    # 相当于下面,会先解析外层括号 再解析里层嵌套
    transposed = []
    for i in range(4):
        transposed.append([row[i] for row in matrix])
    # 当前用内置的函数处理可能更加快一点
    list(zip(*matrix))
    # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
  • 通过列表解析获取笛卡尔积[[i, j] for i in list1 for j in list2]]

生成器表达式

在大数据量的情况下比列表解析要更高效,内存占用率更低,因为他遵循了

FAQ

判断两个list是否相等

判断两个list是否相等

# a & b should be considered equal, because they have exactly the same elements, only in different order.
a = [1, 2, 3, 1, 2, 3]
b = [3, 2, 1, 3, 2, 1]

# O(n): The `Counter()` method is best (if your objects are hashable)
def compare(s, t):
    return Counter(s) == Counter(t)
# O(n log n): The `sorted()` method is next best (if your objects are orderable):
def compare(s, t):
    return sorted(s) == sorted(t)
# O(n * n): If the objects are neither hashable, nor orderable, you can use equality
def compare(s, t):
    t = list(t)   # make a mutable copy
    try:
        for elem in s:
            t.remove(elem)
    except ValueError:
        return False
    return not t

把list当作stack

主要的方法是:

  • append: 入栈
  • pop: 出栈
  • len(list): 查看栈中元素数量

把list当作queue

list本身可以通过append以及pop(index)完成一些列的操作,但是在pop或者在头部insert(0, e)的时候由于要移动移动整个列表的全部元素,所以会很慢,如果想要实现队列的功能,最好使用collections.deque,他专门用于在列表的两边进行快速插入和弹出

from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")
queue  # ["Eric", "John", "Michael", "Terry"]
queue.popleft()  # Eric
queue  # ["John", "Michael", "Terry"]

实现两个列表相减

# list1 - list2
[i for i in list1 if i not in list2]
# 或者新建一个类对减法进行重载
class MyList(list):
    def __init__(self, *args):
        super(MyList, self).__init__(args)

    def __sub__(self, other):
        return self.__class__(*[item for item in self if item not in other])
x = MyList(1, 2, 3, 4)
y = MyList(2, 5, 2)
z = x - y

列表切片空间复杂度

python中列表切片的空间复杂度是O(n),参照这里


⚠️ **GitHub.com Fallback** ⚠️