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]. - 增加一个item到list的尾部
-
list.
extend
(
L
)
-
Extend the list by appending all the items in the given list; equivalent to
a[len(a):] = L. - 通过增加所给list的所有items,从而扩展list
-
list.
insert
(
i,
-
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). - 插入一个item到给定位置
-
list.
remove
(
x
)
-
Remove the first item from the list whose value is
x. It is an error if there is no such item. - 从list里边移除第一个值为x 的item,如果没有这样的item就会出错
-
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.) - 移除list里边给定位置的item,然后返回它。如果用a.pop(),括号里边无东西,表示移除最后一个item
-
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. - 返回list里边第一个元素x的索引
-
list.
count
(
x
)
-
Return the number of times
x appears in the list. - 返回X在list里边出现的次数
-
list.
sort
(
)
- Sort the items of the list, in place.
- 排序list里边的items
-
list.
reverse
(
)
- Reverse the elements of the list, in place.
- 把list里边的elements倒置
-
An example that uses most of the list methods:
- try to type them in your computer!feel better right?
5.1.1. Using Lists as Stacks¶
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
队列的示范
5.1.3. Functional Programming Tools
There are three built-in functions that are very useful when used with lists:
函数编程工具,主要是这三个函数
filter(function,
筛选出这个范围的数字
map(function,
调用function执行每个items并且返回他们的值
reduce(function,
通过调用function挨个执行前两个items后,再执行结果和下一个item到最后,返回一个值。
5.2. The del statement¶
There is a way to remove an item from a list given its index instead of its value: the
顾名思义就是删除,但是它和pop不同,del还可以用来移除list里边的slices和清除整个list
del