Reference:Python官方Document Tutorial
https://docs.python.org/3/reference/datamodel.html#object.__contains__
This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.
In general:
5.1.0list常用方法,
5.1.1. Using Lists as Stacks
5.1.2. Using Lists as Queues
5.1.3. List Comprehensions
5.1.4. Nested List Comprehensions
The list data type has some more methods. Here are all of the methods of list objects:
5.1.0 List常用方法
-
Add an item to the end of the list. Equivalent to
a[len(a):] = [x]
.
list.
append
(
x
)
-
Extend the list by appending all the items from the iterable. Equivalent to
a[len(a):] = iterable
.
list.
extend
(
iterable
)
-
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, anda.insert(len(a), x)
is equivalent toa.append(x)
.
list.
insert
(
i,
x
)
-
Remove the first item from the list whose value is x. It is an error if there is no such item.
list.
remove
(
x
)
-
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.)
list.
pop
(
[
i
]
)
-
Remove all items from the list. Equivalent to
del a[:]
.
list.
clear
(
)
-
Return zero-based index in the list of the first item whose value is 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.
list.
index
(
x
[,
start
[,
end
]
]
)
-
Return the number of times x appears in the list.
list.
count
(
x
)
-
Sort the items of the list in place (the arguments can be used for sort customization, see
sorted()
for their explanation).
list.
sort
(
key=None,
reverse=False
)
-
Reverse the elements of the list in place.
list.
reverse
(
)
-
Return a shallow copy of the list. Equivalent to
a[:]
.
list.
copy
(
)
An example that uses most of the list methods:
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.
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:
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:
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:
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:
or, equivalently:
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:
# 语法 [expression,for 判断语句 (if 判断语句)]
其中expression为每个迭代对象的返回值, if(如果有)在for后面
and it’s equivalent to:
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.
List comprehensions can contain complex expressions and nested functions:
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:
The following list comprehension will transpose rows and columns:
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:
# 不用列表解析,而是用for循环代替实现:
which, in turn, is the same as:
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:
# 特殊:要记住!!
See Unpacking Argument Lists for details on the asterisk in this line.