Python基础二【列表】

 1 #列表【可变数据类型】
 2 spam=['cat', 'bat', 'rat', 'elephant']
 3 print(spam[1])
 4 
 5 spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
 6 print(spam[0])  #['cat', 'bat']
 7 print( spam[0][1])  #'bat'
 8 print(spam[1][4])  # 50
 9 
10 #负数下标:整数值−1 指的是列表中的最后一个下标,−2 指的是列表中倒数第二个下标,以此类推。
11 
12 spam = ['cat', 'bat', 'rat', 'elephant']
13 print(spam[-1])  #elephant
14 
15 #切片取得子列表
16 print(spam[1:2])# 参数:开始下标:结束下标(不包含)
17 
18 #用 len()取得列表的长度
19 
20 print(len(spam))  #4
21 
22 #用下标改变列表中的值
23 spam[1]="today"
24 print(spam)   #['cat', 'today', 'rat', 'elephant']
25 
26 #列表连接  【+ 操作符】
27 list=[' I was ',' not good',' yestody!']
28 print(spam+list)  #['cat', 'today', 'rat', 'elephant', ' I was ', ' not good', ' yestody!']
29 
30 #列表复制【*整数】操作符
31 print(list*2)   #[' I was ', ' not good', ' yestody!', ' I was ', ' not good', ' yestody!']
32 
33 #从列表中删除值【del 语句】
34 del (list[0])
35 print(list)   #[' not good', ' yestody!']
36 
37 #列表连接
38 who='I';
39 list= [who]+list
40 print(list)   #['I', ' not good', ' yestody!']
41 
42 #列表迭代
43 for i in range(len(list)):
44     print(list[i])
45 
46 #批量赋值
47 word1,word2,word3=list
48 print(word3)# ' yestody'
49 
50 #检查列表中是否包含某值【in , not in】
51 print( 'wang' in list)#False
52 print('wanng' not in list) #True
53 
54 #获取某字符串在列表中的下标; 注意,如果列表中有多个,则只返回第一次出现的下标;不在列表中时,报ValueError
55 print(list.index('I')) #0
56 list=list+['I']
57 print(list) #['I', ' not good', ' yestody!', 'I']
58 print(list.index('I')) #0
59 #print(list.index('sorry')) #ValueError: 'sorry' is not in list
60 
61 #列表中添加值 append() 和 insert()
62 list.append('stupid')#将数据添加到末尾
63 print(list)#['I', ' not good', ' yestody!', 'I', 'stupid']
64 list.insert(1,'dog')#第一个参数是要插入的下标,第二个参数是值
65 print(list)#['I', 'dog', ' not good', ' yestody!', 'I', 'stupid']
66 
67 #从列表中删除值【remove()】
68 list.remove('stupid')#注意:此方法 没有返回值
69 print(list)#['I', 'dog', ' not good', ' yestody!', 'I']
70 
71 #列表排序【sort()方法,当场对序列排序,返回空;不能对既有数字又和字符串的列表进行比较】
72 intList=[1,5,10,8,2,3]
73 print(intList)
74 intList.sort()
75 print(intList)#[1, 2, 3, 5, 8, 10]
76 intList.sort(reverse=True)
77 print(intList)#[10, 8, 5, 3, 2, 1]
78 print(intList.sort(reverse=True))#None
79 
80 intStrList=['Alice','Bob',1,7,3]
81 intStrList.sort()#TypeError: '<' not supported between instances of 'int' and 'str'
82 
83 #sort()对字符串列表排序时,使用的“ASCII”字符顺序而不是实际的字典顺序,A-Z然后a-z
84 #如果要按字典排序,增加参数 key=str.lower
85 # strList.sort(key=str.lower)

 

posted @ 2022-10-12 12:59  山顶听风  阅读(34)  评论(0)    收藏  举报