5. 数据结构

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

5.1. 更多关于列表

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

列表。 append ( x )

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

列表。 extend ( iterable )

Extend the list by appending all the items from the iterable. Similar to a[len(a):] = iterable .

列表。 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) 相当于 a.append(x) .

列表。 remove ( x )

Remove the first item from the list whose value is equal to x . It raises a ValueError 若没有这样的项。

列表。 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. It raises an IndexError if the list is empty or the index is outside the list range.

列表。 clear ( )

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

列表。 index ( x [ , start [ , end ] ] )

Return zero-based index in the list of the first item whose value is equal to x 。引发 ValueError 若没有这样的项。

可选自变量 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 自变量。

列表。 count ( x )

Return the number of times x appears in the 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 ( )

Reverse the elements of the list in place.

列表。 copy ( )

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

An example that uses most of the list methods:

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting at position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'