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)

 

原文地址:http://www.cnblogs.com/ltsgsh/p/16784155.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性