zoukankan      html  css  js  c++  java
  • Python数据结构(一)

    5. Data Structures

    This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.

    这一章节将更详细的描述你已经学到的东西,并增加一些知识。

    5.1. More on Lists

    The list data type has some more methods. Here are all of the methods of list objects:

    列表数据类型有很多方法,这里列出了列表对象的一下方法:

    list.append(x)

    Add an item to the end of the list. Equivalent to a[len(a):] = [x].

    在列表的尾部增加一个元素,相当于 a[len(a):] = [x]。

    list.extend(L)

    Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L.

    在列表的尾部增加另一个列表的所有元素,相当于 a[len(a):] = L。

    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).

    在指定的位置增加一个元素,第一个参数是插入元素的索引,也就是在该元素之前插入元素x。因此a.insert(0,x)就是在第一个元素前插入x。 a.insert(len(a),x)相当于a.append(x)。

    list.remove(x)

    Remove the first item from the list whose value is x. It is an error if there is no such item.

    移除列表中第一个值等于x的元素,如果找不到值为x的元素,则返回错误。

    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.)

    移除列表中指定位置的元素,并返回该元素。如果没有指定索引,a.pop()移除最后一个元素,并返回该元素。(中括号表示该参数是可选的,而不是说一定得指定索引。你将会在Python库参考中经常看到这种符号。)

    list.clear()

    Remove all items from the list. Equivalent to del a[:].

    移除列表中的所有元素,相当于 del a[:]

    list.index(x)

    Return the index in the list of the first item whose value is x. It is an error if there is no such item.

    返回列表中第一个值为x的索引,如果没有该值,则返回错误。

    list.count(x)

    Return the number of times x appears in the list.

    返回值x在列表中出现的次数。

    list.sort()

    Sort the items of the list in place.

    给列表中的元素排序。

    list.reverse()

    Reverse the elements of the list in place.

    反转列表中的元素。

    list.copy()

    Return a shallow copy of the list. Equivalent to a[:].

    返回列表的拷贝,相当于返回 a[:]。

    An example that uses most of the list methods:

    该例子使用了列表的大部分方法:

    >>> a = [66.25, 333, 333, 1, 1234.5]
    >>> print(a.count(333), a.count(66.25), a.count('x'))
    2 1 0
    >>> a.insert(2, -1)
    >>> a.append(333)
    >>> a
    [66.25, 333, -1, 333, 1, 1234.5, 333]
    >>> a.index(333)
    1
    >>> a.remove(333)
    >>> a
    [66.25, -1, 333, 1, 1234.5, 333]
    >>> a.reverse()
    >>> a
    [333, 1234.5, 1, 333, -1, 66.25]
    >>> a.sort()
    >>> a
    [-1, 1, 66.25, 333, 333, 1234.5]
    >>> a.pop()
    1234.5
    >>> a
    [-1, 1, 66.25, 333, 333]

    You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. [1] This is a design principle for all mutable data structures in Python.

    你可能已经注意到像insert,remove或sort方法仅仅只是修改列表但不返回任何值,其实他们都默认返回None。这是所有在Python中可变数据类型的设计原则。

    5.1.1. Using Lists as Stacks

    The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

    列表的方法使得列表可以很容易作为一个堆栈。在堆栈中增加一个元素,可以使用append()。从栈顶获取一个元素,可以使用pop()。例如:

    >>> stack = [3, 4, 5]
    >>> stack.append(6)
    >>> stack.append(7)
    >>> stack
    [3, 4, 5, 6, 7]
    >>> stack.pop()
    7
    >>> stack
    [3, 4, 5, 6]
    >>> stack.pop()
    6
    >>> stack.pop()
    5
    >>> stack
    [3, 4]

    5.1.2. Using Lists as Queues

    It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

    列表也可以作为队列来使用。然而它作为队列可能不是很有效率。在列表的尾部增加或移除元素很快,但在列表的头部插入或移除元素很慢(因为所有的元素都要往前移动一位)。

    To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:

    要实现队列,可以使用collection.deque。deque在两端做插入和移除操作都很快。例如:

    >>> from collections import deque
    >>> queue = deque(["Eric", "John", "Michael"])
    >>> queue.append("Terry")           # Terry arrives
    >>> queue.append("Graham")          # Graham arrives
    >>> queue.popleft()                 # The first to arrive now leaves
    'Eric'
    >>> queue.popleft()                 # The second to arrive now leaves
    'John'
    >>> queue                           # Remaining queue in order of arrival
    deque(['Michael', 'Terry', 'Graham'])

    5.1.3. List Comprehensions

    List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

    List comprehensions提供了一个简洁的方式来创建列表。一般程序常常通过操作另一个序列或可迭代对象,然后将这些这些返回的元素来作为列表的元素,或者是创建这些元素的子列表。

    For example, assume we want to create a list of squares, like:

    例如:假设我们想创建一个存储元素平方计算后的的列表:

    >>> squares = []
    >>> for x in range(10):
    ...     squares.append(x**2)
    ...
    >>> squares
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

     Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:

    注意,当循环结束后,变量x仍然存在。

    squares = list(map(lambda x: x**2, range(10)))

    or, equivalently:

    或者,相当于:

    squares = [x**2 for x in range(10)]

    which is more concise and readable.

    这种表达式更加简单和可读性。

    A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:

    这个List comprehensions包括如下一个部分,首先是方括号括起来,方括号中包含一个for子句,后面也可以有0个或多个for或if子句。通过for或if筛选之后的结果作为列表的元素。例如下面的例子,如果两个列表中的元素不相等,则合并:

    >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
    [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

    它相当于:

    >>> combs = []
    >>> for x in [1,2,3]:
    ...     for y in [3,1,4]:
    ...         if x != y:
    ...             combs.append((x, y))
    ...
    >>> combs
    [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

    Note how the order of the for and if statements is the same in both these snippets.

    这两个代码片段中,for语句和if语句的顺序是相同的。

    If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.

    一个表达式是个元组(比如上一个例子中的(x,y)),它必须加上括号。

    >>> vec = [-4, -2, 0, 2, 4]
    >>> # create a new list with the values doubled
    >>> [x*2 for x in vec]
    [-8, -4, 0, 4, 8]
    >>> # filter the list to exclude negative numbers
    >>> [x for x in vec if x >= 0]
    [0, 2, 4]
    >>> # apply a function to all the elements
    >>> [abs(x) for x in vec]
    [4, 2, 0, 2, 4]
    >>> # call a method on each element
    >>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
    >>> [weapon.strip() for weapon in freshfruit]
    ['banana', 'loganberry', 'passion fruit']
    >>> # create a list of 2-tuples like (number, square)
    >>> [(x, x**2) for x in range(6)]
    [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
    >>> # the tuple must be parenthesized, otherwise an error is raised
    >>> [x, x**2 for x in range(6)]
      File "<stdin>", line 1, in ?
        [x, x**2 for x in range(6)]
                   ^
    SyntaxError: invalid syntax
    >>> # flatten a list using a listcomp with two 'for'
    >>> 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]

    5.1.4. Nested List Comprehensions

    The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

    Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:

    看看下面的例子,一个3 x 4的矩阵用一个列表表示:这个列表包含3个子列表,每个子列表含有4个元素。

    >>> matrix = [
    ...     [1, 2, 3, 4],
    ...     [5, 6, 7, 8],
    ...     [9, 10, 11, 12],
    ... ]

    The following list comprehension will transpose rows and columns:

    下面的List comprehensions将会对调矩阵的行和列:

    >>> [[row[i] for row in matrix] for i in range(4)]
    [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

    As we saw in the previous section, the nested listcomp is evaluated in the context of the for that follows it, so this example is equivalent to:

    正如我们上面所看到的,这个例子相当于:

    >>> transposed = []
    >>> for i in range(4):
    ...     transposed.append([row[i] for row in matrix])
    ...
    >>> transposed
    [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

    which, in turn, is the same as:

    同样也可以是这种形式:

    >>> transposed = []
    >>> for i in range(4):
    ...     # the following 3 lines implement the nested listcomp
    ...     transposed_row = []
    ...     for row in matrix:
    ...         transposed_row.append(row[i])
    ...     transposed.append(transposed_row)
    ...
    >>> transposed
    [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

    In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:

    在实际的编写过程中,你应该使用内置的函数来实现。zip()函数非常适宜做这样的事情:

    >>> list(zip(*matrix))
    [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] 
  • 相关阅读:
    Jsp+Servlet实现文件上传下载——前台页面开发
    【软考】——原码、反码、补码、移码
    【NCRE】——c# 给PPT判分
    [RN] React Native Image 实现placeholder占位图
    [PHP] Elasticsearch 6.4.2 的安装和使用
    [RN] 使用 Genymotion 导致 ” Genymotion 已连接,但无法访问互联网 “ 的错误
    [RN] React Native 分享弹窗 ShareAlertDialog
    [RN] React Navigation 使用中遇到的显示 问题 汇总
    [RN] React Native Fetch请求设置超时
    [RN] React Native 滚动跳转到指定位置
  • 原文地址:https://www.cnblogs.com/lijie-vs/p/4338206.html
Copyright © 2011-2022 走看看