看python官方说明学python-list-列表

来源:互联网 发布:梅西c罗数据对比 编辑:程序博客网 时间:2024/06/05 11:08

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)

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

list.extend(L)

Extend the list by appendingall the items in the given list. Equivalent to a[len(a):] = L. 这里是切片的意思。比如说,a有6个元素,第6个元素的索引是5,len(a)=6,将L的值赋到这个a[6]的元素,这样a就有7个元素了。

list.insert(ix)

Insert an item at a given position. The first argument is the index of the element before which to insert, soa.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

list.remove(x)

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

list.pop([i])

Remove the itemat the given positionin the list,and return it.If no index is specifieda.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.)

list.index(x)

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

list.count(x)

Return the number of times x appears in the list.

list.sort()

Sort the items of the list in place.

list.reverse()

Reverse the elements of the list in place.

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)#这里只返回第一个找到的333值的索引1>>> a.remove(333) #这里也是删除第一个找到的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]

You might have noticed that methods like insertremove or sort that modify the list have no return value printed – they return None. [1] This is a design principle for all mutable data structures in 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:

>>>
>>> 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:

#下面的这些可以说变成了"first-into-rightest, leftest-out"  跟"first-in, first-out" 在pop的时候选择方向相反。

>>>
>>> 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 arrivaldeque(['Michael', 'Terry', 'Graham']) #这招在以后的 解决实际问题 “一个岛上只有三个人能来当岛主,后来来的,顶掉第一个先来的。岛主容量只有3人。”

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.

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]

We can obtain the same result with:

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

This is also equivalent to squares = list(map(lambda x: x**2, range(10))), but it’s more concise and readable.

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

>>>
>>> [(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)]

and it’s equivalent to:

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

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

>>>
>>> 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]

List comprehensions can contain complex expressions and nested functions:

>>>
>>> from math import pi>>> [str(round(pi, i)) for i in range(1, 6)]['3.1', '3.14', '3.142', '3.1416', '3.14159']

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:

>>>
>>> matrix = [...     [1, 2, 3, 4],...     [5, 6, 7, 8],...     [9, 10, 11, 12],    # 注意,这里12后面没有","没有逗号。官方的错误了,这样matrix里面将有4个元素,而第四个为空!!! 官方wiki错误了!... ]

The following list comprehension will transpose rows and columns:

这里,运算从右向左,进行完了之后,进入右边,因为右边有方括号,所以输出的将是数列。

当完成第一个row[0](来自于matrix[0])之后,for row in martix 又进行输出row[0],只不过这次是matrix[1]中的,...,一直输出到matrix[2]完成后跳出左边的循环,继续右边for i in range(4)的循环。目的是为了遍历输出martix[0], martix[1], matrix[2] 中的所有索引为i 的元素。

>>>
>>> [[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:


>>>
>>> list(zip(*matrix))[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] #注意这里输出的全部变成了tuple元组了,跟上面的不同。zip是一种特殊的类型,在python3中

See Unpacking Argument Lists for details on the asterisk in this line.


zip(*iterables)

Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to:

def zip(*iterables):    # zip('ABCD', 'xy') --> Ax By    sentinel = object()    iterators = [iter(it) for it in iterables]    while iterators:        result = []        for it in iterators:            elem = next(it, sentinel)            if elem is sentinel:                return            result.append(elem)        yield tuple(result)

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).

zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, use itertools.zip_longest() instead.

zip() in conjunction with the * operator can be used to unzip a list:

>>>
>>> x = [1, 2, 3]>>> y = [4, 5, 6]>>> zipped = zip(x, y)>>> list(zipped)[(1, 4), (2, 5), (3, 6)]>>> x2, y2 = zip(*zip(x, y))>>> x == list(x2) and y == list(y2)True