注:
来自:《Python 编程 从入门到实践》
调试: Sublime Text2 Python3
python的列表是由一系列特定顺序排列的元素组成,用 [] 来表示,且数据类型可不同,比如:
strList = ["one", "two", "thress"] numList = [1,2,3,'msg']print(strList) print(numList) >>> ['one', 'two', 'thress'] [1, 2, 3, 'msg']
在python中,如果访问列表元素,起始索引从0开始,因此如果其列表有元素4个,其最后一个元素的索引为3。Python提供了一种特殊的语法,将索引指定为-1,表示获取最后一个元素,依次类推。比如:
strList = ["one", "two", "three"] print(strList[0]) #one print(strList[-1]) #three print(strList[-2]) #two
其列表元素的一些常用用法:
strList = ["A", "two", "three"] # ---------------- 修改元素 ---------------- # 修改列表元素,可根据列表名的索引,直接替换成新元素即可 strList[0] = 'one' print(strList) #['one', 'two', 'three'] # ---------------- 添加元素 ---------------- # 在列表末尾添加新元素,可使用方法:append() strList.append('five') print(strList) #['one', 'two', 'three', 'five'] # 在列表指定位置插入元素,可使用方法:insert() strList.insert(3,'four') print(strList) #['one', 'two', 'three', 'four', 'five'] ## 注意,如果你添加的位置索引过大或过小,会默认为结尾索引或起始索引 strList.insert(100,'six') print(strList). #['one', 'two', 'three', 'four', 'five', 'six'] strList.insert(-80,'zero') print(strList) #['zero', 'one', 'two', 'three', 'four', 'five', 'six'] # ---------------- 删除元素 ---------------- # 在列表中删除元素,可使用方法: del ## 注意,其索引一定要为列表内元素的索引,否则会出错 del strList[0] print(strList) #['one', 'two', 'three', 'four', 'five', 'six'] del strList[-1] print(strList). #['one', 'two', 'three', 'four', 'five'] # 使用 del 删除元素,会永久删除,如果我们想继续使用,可用方法:pop() # pop方法,其参数为空,表示移除末尾元素,否则就是移除指定位置元素 print(strList) #['one', 'two', 'three', 'four', 'five'] ## 移除列表末尾元素 popStr = strList.pop() print(strList) #['one', 'two', 'three', 'four'] print(popStr) #five ## 移除列表指定位置元素,其索引一定要为列表内元素的索引,否则会出错 popStr = strList.pop(1) print(strList) #['one', 'three', 'four'] print(popStr) #two # ---------------- 排序元素 ---------------- # 对列表元素永久排序,可使用方法sort(),默认是升序 strList.sort() print(strList) #['four', 'one', 'three'] #如果是降序,可在sort方法中传递参数reverse = True strList.sort(reverse = True) print(strList) #['three', 'one', 'four'] # 对列表元素进行临时排序,可使用方法sorted(),跟sort的用法类似,只是列表的顺序不变 strTab = ['a','c','e','d'] print(sorted(strTab)) #['a', 'c', 'd', 'e'] print(sorted(strTab,reverse = True)) #['e', 'd', 'c', 'a'] print(strTab) #['a', 'c', 'e', 'd'] # ---------------- 其它 ---------------- # 反序打印列表,可使用方法:reverse() strTab = ['a','b','c','d'] strTab.reverse() print(strTab) #['4', '3', '2', '1'] # 确定列表长度,可使用方法: len() tabLen = len(strTab) print('长度:' + str(tabLen)) #长度:4 print(strTab[tabLen - 1]) #a
列表循环可使用for循环:
msg = {'one','two','three'} for value in msg: print(value) print('End!!!') #注意缩行 #输出: one two three End!!!
如果检查某元素是否在列表中,可使用:in 或者 not in
strTab = ('hello','python') # 检查某元素是否在列表中,使用 in ,如果存在返回True,否则False print('hello' in strTab) #True print('hell' in strTab) #False # 检查某元素是否不在列表中,使用 not in ,如果不存在返回True,否则False print('hello' not in strTab) #False print('hell' not in strTab) #True