Python基础(1)-List对象可用的11个方法
结合Python documentation 3.8.1 及个人理解总结。
1. list.append(x)–非常常用
Add an item to the end of the list. Equivalent to a[len(a):] = [x].
2. list.extend(iterable)
Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.
在list a的末尾添加一个iterable对象。
很少用到,功能看起来与append类似。
实际和append的区别在于:
有a = [1,2,3,4,5], b = [6,7,8]
a.append(b)—a = [1,2,3,4,5,[6,7,8]]
a.extend(b)—a = [1,2,3,4,5,6,7,8]
3. 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).
在给定的位置i插入元素x.
4. list.remove(x)–常用
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
根据参数x在列表中找到相同的值进行删除。如果找不到会报错ValueError。
5. 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(i)或者a.pop()------[]表示该参数选填
6. list.clear()
Remove all items from the list. Equivalent to del a[:].
用remove或pop删除特定元素,用clear删除所有元素。
7.list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is equal to 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.
根据指定的值返回元素的下标,列表中不存在该值就报错ValueError.
可以使用start和end选择subsequence,但是返回的下标是‘’绝对下标‘’。
比如想要的元素下标是8,使用start,end是4,9时,返回的下标是还是8。
8. list.count(x)
Return the number of times x appears in the list.
统计并返回元素x在列表中出现的次数。
9. 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).
直接在原list上进行排序。
对比sorted()方法,根据传入的iterable对象,重新生成一个排序的iterable对象。
10. list.reverse()
Reverse the elements of the list in place.
逆转链表
11. list.copy()
Return a shallow copy of the list. Equivalent to a[:].
如果有new=old.copy(),对b做修改是否影响a?
看下面例子:(参考:https://www.cnblogs.com/Black-rainbow/p/9577029.html)
old = [1,[1,2,3],3]
new = old.copy()
print('Before:')
print(old)
print(new)
new[0] = 3
new[1][0] =3
print('After:')
print(old)
print(new)
输出:
Before:
[1,[1,2,3],3]
[1,[1,2,3],3]
After:
[1,[3,2,3],3]
[3,[3,2,3],3]
外层深拷贝,内层(old中第二个元素nested object)浅拷贝。