首页 > 代码库 > python开发基础:列表操作

python开发基础:列表操作

一,列表操作

 1 #!/usr/bin/env python
 2 #_*_coding:utf-8_*_
 3 
 4 # l=[1,2,3] #l=list([1,2,3])
 5 # print(type(l))
 6 
 7 #pat1===》优先掌握部分
 8 #  索引
 9 #
10 #     切片
11 # l=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘]
12 
13 # print(l[1:5])
14 # print(l[1:5:2])
15 # print(l[2:5])
16 # print(l[-1])
17 
18 
19 #了解
20 # l=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘]
21 # print(l[-1:-4]) #结果为空,因为无法从右到左
22 # print(l[-4:-1:2])
23 # print(l[-2:])
24 
25 #     追加
26 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘]
27 # hobbies.append(‘girls‘)
28 # print(hobbies)
29 
30 #     删除
31 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘]
32 # # x=hobbies.pop(1) #不是单纯的删除,是删除并且把删除的元素返回,我们可以用一个变量名去接收该返回值
33 # print(hobbies.pop(1))
34 # print(hobbies)
35 
36 # x=hobbies.pop(0)
37 # print(x)
38 #
39 
40 #了解
41 # del hobbies[1] #单纯的删除
42 # hobbies.remove(‘eat‘) #单纯的删除,并且是指定元素去删除,没有会报错
43 
44 #     长度
45 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘]
46 # print(len(hobbies))
47 
48 #     包含in
49 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘]
50 # print(‘sleep‘ in hobbies)
51 
52 # msg=‘hello world egon‘
53 # print(‘egon‘ in msg)
54 
55 
56 ##pat2===》掌握部分
57 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘,‘eat‘,‘eat‘]
58 # hobbies.insert(1,‘walk‘)
59 # hobbies.insert(1,[‘walk1‘,‘walk2‘,‘walk3‘])
60 # print(hobbies)
61 
62 # print(hobbies.count(‘eat‘)) #统计元素有多少个
63 # print(hobbies)
64 # hobbies.extend([‘walk1‘,‘walk2‘,‘walk3‘]) #2个列表合在一起
65 # print(hobbies)
66 # l = [‘walk1‘,‘walk2‘,‘walk3‘]
67 # hobbies.extend(l)
68 # print(hobbies)
69 
70 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘,‘eat‘,‘eat‘] #查找,返回索引,没有找到报错
71 # print(hobbies.index(‘eat‘))
72 
73 
74 #pat3===》了解部分
75 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘,‘eat‘,‘eat‘]
76 # hobbies.clear()   #清空
77 # print(hobbies)
78 
79 # l=hobbies.copy() #复制
80 # print(l)
81 
82 # l=[1,2,3,4,5] #倒序
83 # l.reverse()
84 # print(l)
85 
86 # l=[100,9,-2,11,32]
87 # # l.sort(reverse=True) #排序,默认从小到大
88 # # print(l)

 

python开发基础:列表操作