赛博红兔的科技博客

CyberHongTu shares news, insights, and musings on fascinating technology subjects.


和我一起玩Python:10. 列表的方法

今天咱们聊聊Python里列表的各种玩法。得强调的是,列表的这些方法会直接改变列表本身,这点和字符串不一样。这些方法大概分五类:增加元素、删除元素、排序、小练习,还有和字符串类似的方法。增加元素用的方法有append()、insert()和extend()。删除呢,可以用remove()、pop()、clear()。排序方面有reverse()、sort()和sorted()。还有个小练习,比较一下把列表赋值给变量和复制列表有啥不同。最后,咱们会学学count()方法和in/not in语句,这俩和字符串里的方法差不多。

List Method List

MethodDescription
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position and return its value
remove()Removes the item with the specified value
reverse()Removes the element at the specified position and returns its value
sort()Sorts the list
NoteBold methods can also be used as Tuple Methods

列表的方法列表

方法说明
append()在列表末尾添加元素
clear()删除列表中的所有元素
copy()返回列表的副本
count()返回具有指定值的元素的数量
extend()将列表(或任何可迭代的)的元素添加到当前列表的末尾
index()返回具有指定值的第一个元素的索引
insert()在指定位置添加元素
pop()删除指定位置的元素并返回其值
remove()删除具有指定值的项目
reverse()反转列表的顺序
sort()对列表进行排序
注意加粗的方法也可以用作元组的方法


Leave a comment