随着我分享我每天学习python的进度,我越来越清楚和明显地看到,同时学习和分享解释概念有助于巩固知识,也是提升自己能力的一种有效方式。
列表
列表函数
就像字符串一样,Python为我们提供了一些内置方法来对列表数据类型执行一些操作。同样,在对象上的 .
运算符之后调用方法。可以根据动作类型对动作进行分类。
下图中的方法是列表专有的内置方法,请熟记于心。
方法 |
作用 |
append(obj) |
在列表末尾添加新的对象 |
count(obj) |
统计某个元素在列表中出现的次数 |
extend(seq) |
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
index(obj) |
从列表中找出某个值第一个匹配项的索引位置 |
insert(index, obj) |
将对象插入列表 |
pop(obj=list[-1]) |
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
remove(obj) |
移除列表中某个值的第一个匹配项 |
reverse() |
反向列表中元素 |
sort([func]) |
对原列表进行排序 |
copy() |
复制列表 |
clear() |
清空列表,等于del lis[:] |
注意:其中的类似 append,insert, remove 等方法会修改列表本身,并且没有返回值(严格的说是返回None)。
添加列表(append, insert, extend)
scores = [44,48,55,89,34] scores.append(100) # Append adds a new item to the end print(scores) # [44, 48, 55, 89, 34, 100] scores.insert(0, 34) # Inserts 34 to index 0 scores.insert(2, 44) # Inserts 44 to index 2 print(scores) # [34, 44, 44, 48, 55, 89, 34, 100] scores.extend([23]) # Extend takes an iterable (loopable items) and adds to end of list print(scores) # [34, 44, 44, 48, 55, 89, 34, 100, 23] scores.extend([12,10]) print(scores) # [34, 44, 44, 48, 55, 89, 34, 100, 23, 12, 10]
这里有一个小问题。这些方法将元素添加到列表中 ,不返回任何值。
scores = [44,48,55,89,34] newScores = scores.append(100) print(newScores) # None newScores = scores.insert(0,44) print(newScores) # None
从列表中删除项目(pop, remove, clear)
languages = ['C', 'C#', 'C++'] languages.pop() print(languages) # ['C', 'C#'] languages.remove('C') print(languages) # ['C#'] languages.clear() print(languages) # []
获取索引和计数(index, count)
alphabets = ['a', 'b', 'c'] print(alphabets.index('a')) # 0 (Returns the index of the element in list print(alphabets.count('b')) # 1 (counts the occurence of an element
排序、反转和复制列表(sort,reverse,copy)
numbers = [1,4,6,3,2,5] numbers.sort() # Sorts the list items in place and returns nothing print(numbers) # [1, 2, 3, 4, 5, 6] #Python also has a built in sorting function that returns a new list sorted_numbers = sorted(numbers) # note - this is not a method print(sorted_numbers) # [1, 2, 3, 4, 5, 6] numbers.reverse() # reverse the indices in place print(numbers) # [6, 5, 4, 3, 2, 1] numbers_clone = numbers.copy() # another approach is numbers[:] print(numbers_clone) # [6, 5, 4, 3, 2, 1]
列表模式
最后,我探讨了一些经常与列表一起使用的常见模式,例如我已经提到的反转、将列表加入字符串和复制。
avengers = ['ironman', 'spiderman', 'antman', 'hulk'] cloned_avengers = avengers[::1] # very commonly used pattern reversed_avengers = avengers[::-1] # discussing again because it is also very common merge_avengers = ' '.join(avengers) # used to join list into string print(cloned_avengers)