直接上代码:
def listAction():
#2.0 列表
print "将字符串转成列表",list("hello");
exl = list("hello");
print exl[0]; ##读取列表中item
print ''.join(exl); ## 将列表转成字符串
#2.0.1 对列表的操作---添加item
exList = [None]*10;
#对列表添加item
#下标赋值, add item,append,insert,extend
print "初始化列表: ",exList
#下标赋值--会改变列表的值
exList[0]="test";
print "exList items: ",exList;
#分片add item 添加在列表项的左后位置,如果有None 将代替None
exList[1:3] = ["fuck","james"]
print "分片添加item 后: ",exList
#apend add item
##始终是在列表的最后位置,并扩展列表的长度
exList.append("mother")
print "apend add item",exList
#insert add item
#在指定列表的位置前面插入item,会改变列表的长度
exList.insert(3,"mother");
print "insert add item ",exList
#extend add items
#在列表项的最后位置添加多个item 会改变列表的长度
ext = ["add","del"]
exList.extend(ext)
print "用extend 给列表添加多个item",exList
#2.0.2 对列表的操作---统计item 出现在列表中的次数
#count
print "count 统计 列表中item在list中出现的次数:", exList.count("test");
#2.0.3 对列表的操作---查找列表中第一个匹配项的位置索引
#index 查找列表中第一个匹配项的位置索引,如果没有匹配就会报异常
print "查找匹配项",exList.index("james")
#2.0.4 对列表的操作---删除
#pop 删除列表最后的item
exList.pop();
print "删除后:",exList
# remove 删除莫一项
exList.remove("test")
print "用remove 删除列表项后:",exList;
#2.1 列表的排序操作
def sortTest():
sortList = [1,4,6,3,8]
#用sort 排序 会改变整个列表的item值
sortList.sort();
print "sort排序后的列表:",sortList;
#如果用sorted 只是返回一个排序后的列表的副本,原来的列表不变
sortList = [1,4,6,3,8]
tem = sorted(sortList);
print "用sorted排序后的列表:",tem;
print "原来的列表:",sortList;
#use reverse 去反序列表 原来的列表只会变
sortList = [1,4,6,3,8]
sortList.reverse()
print "用reverse 去列表的反序排列",sortList
#用reversed去反序列表 原来的列表不变,返回一个迭代器iterator
#可以转换成list
sortList = [1,4,6,3,8]
temp = reversed(sortList)
list(temp) #将迭代器转成list
print "去反序后的列表:",tem;
print "运来的列表:",sortList;