Python列表常用方法和函数

1、list.append(obj)

  在列表末尾添加一个元素,如:

lst = ['I', 'like', 'python']
lst.append('!')
print(lst)

  运行结果:['I', 'like', 'python', '!']  注:原列表中更新,不能赋值给其他变量

2、list.count(obj)

  统计某个元素在列表中出现的次数,如:

lst = ['I', 'like', 'python', 'python', 'python']
count = lst.count('python')
print(count)

  运行结果:3  注:返回结果为int型

3、list.extend(seq)

  在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表),如:

lst = ['I', 'like', 'python']
lst.extend(['You','too?'])
print(lst)

  运行结果:['I', 'like', 'python', 'You', 'too?']  注:原列表中更新,不能赋值给其他变量

4、list.index(obj)

  从列表中找出某个值第一个匹配项的索引位置,如:

lst = ['I', 'like', 'python', '人生', '苦短', '我用', 'python']
print(lst.index('python'))

  运行结果:2

5、list.insert(index, obj)

  将对象插入列表指定的位置,如:

lst = ['人生', '苦短', 'python']
lst.insert(2, '我用')
print(lst)

  运行结果:['人生', '苦短', '我用', 'python']

6、list.pop([index=-1])

  移除列表中的一个元素(默认最后一个元素),并且返回该元素的值,如:

lst = [1, 2, 22, 25, 12, 20]
a = lst.pop()  # 默认移除最后一个元素
b = lst.pop(2)  # 移除第三个元素
print(a, b)
print(lst)

  运行结果:a=20,b=22,lst=[1, 2, 25, 12]

7、list.remove(obj)

  移除列表中某个值的第一个匹配项,如:

lst = [1, 2, 22, 25, 22, 18]
lst.remove(22)
print(lst)

  运行结果:[1, 2, 25, 22, 18]  第二个22未被remove

8、list.reverse()

  反向列表中元素,如:

lst = [1, 2, 22, 25, 22, 18]
lst.reverse()
print(lst)

  运行结果:[18, 22, 25, 22, 2, 1]

9、list.sort(cmp=None, key=None, reverse=False)

  对原列表进行排序,没有返回值,默认升序,reverse=True为降序(cmp和key暂时省略)

lst = [1, 2, 22, 25, 22, 18]
lst.sort()  # 默认升序
print(lst)
lst.sort(reverse=True)  # 降序排列
print(lst)

  运行结果:[1, 2, 18, 22, 22, 25],[25, 22, 22, 18, 2, 1]  注:没有返回值,不能赋值给其他变量

10、list.copy()函数

  用于复制一个所给的列表,返回一个对象,如:

lst = [1, 2, 22, 25, 22, 18]
newList = lst.copy()
print(newList)

  运行结果:[1, 2, 22, 25, 22, 18]

11、len(list)、max(list)、min(list)函数

  分别是获取列表元素个数,元素最大值和元素最小值,如:

lst = [1, 2, 22, 25, 22, 18]
print(len(lst))     # 获取元素个数
print(max(lst))     # 获取最大元素
print(min(lst))     # 获取最小元素

  运行结果分别是:6,25,1

posted @ 2021-12-09 22:26  童薰  阅读(320)  评论(0编辑  收藏  举报