python之列表方法

列表方法

一、调用方法:

object.method(arguements)

方法调用与函数调用很像,只是在方法名前加上对象和句号。

1.append

定义:将一个对象附加到列表末尾

函数:lst.append(char)

代码:

1 lst = [1,2,3]
2 lst.append(4)
3 print(lst)

结果:

1 [1, 2, 3, 4]

2.clear

定义:清除列表内容

函数:lst.clear()

代码:

1 lst = [1,2,3]
2 lst.clear()
3 print(lst)

结果:

1 []

3.copy

定义:复制列表;复制成一个新列表后,再进行对新列表进行操作,不会影响到原列表

函数:lst.copy

代码:

1 lst = [1,2,3]
2 lst_1 = lst.copy()  #copy操作
3 lst_1.append(5) #在copy的列表中增加5
4 print(lst)
5 print(lst_1)

结果:

1 [1, 2, 3]
2 [1, 2, 3, 5]

4.count

定义:计算列表中元素出现的次数

函数:lst.count(char)

代码:

1 lst = [1,2,3,4,4,4,4,4,4,44,4,4,4,4,4,4,4,4,4,4,4,4]
2 lst_1 = lst.count(4)
3 print(lst_1)

结果:

1 18

5.extend

定义:将一个列表中元素拓展到另一个列表中

函数:lst.extend(lst1)

代码:

1 lst = [1,2,3,4,4,4,4,4,4,44,4,4,4,4,4,4,4,4,4,4,4,4]
2 lst_2 = ['java',1,4,5,'looo','python']
3 lst.extend(lst_2)
4 print(lst)

结果

1 [1, 2, 3, 4, 4, 4, 4, 4, 4, 44, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 'java', 1, 4, 5, 'looo', 'python']

6.index

定义:查询列表中的元素,并返回其元素的索引位置

函数:lst.index(char)

代码:

1 lst = [1,2,3,'java',1,4,5,'looo','python']
2 lst_1 = lst.index('python')
3 print(lst_1)

结果:

8

7.insert

定义:在列表中插入对象,插入方式是通过索引来增加元素

函数:lst.insert(索引,‘char’)

代码:

1 lst = [1,2,3,'java',1,4,5,'looo','python']
2 lst.insert(3,'LOL')
3 print(lst)

结果:

1 [1, 2, 3, 'LOL', 'java', 1, 4, 5, 'looo', 'python']

8.pop

定义:移除列表中的最后一个元素

函数:lst.pop()

代码:

1 lst = [1,2,3,'java',1,4,5,'looo','python']
2 lst.pop()
3 print(lst)

结果:

1 [1, 2, 3, 'java', 1, 4, 5, 'looo']

9.remove

定义:移除列表中指定的元素

函数:lst.remove(‘元素’)

代码:

1 lst = [1,2,3,'java',1,4,5,'looo','python']
2 lst.remove(1)
3 print(lst)

结果:

1 [2, 3, 'java', 1, 4, 5, 'looo', 'python']

10.reverse

定义:对列表进行反向排序

函数:lst.reverse()

代码:

1 lst = [1,2,3,'java',1,4,5,'looo','python']
2 lst.reverse()
3 print(lst)

结果:

1 ['python', 'looo', 5, 4, 1, 'java', 3, 2, 1]

11.sort

定义:对列表进行就地排序

函数:lst.sort()

代码:

1 lst = [4,6,2,1,90,66,6]
2 lst.sort()
3 print(lst)

结果:

1 [1, 2, 4, 6, 6, 66, 90]

猜你喜欢

转载自www.cnblogs.com/aszeno/p/10227019.html