一组有序项目的集合可变的数据类型【可进行增删改查】列表中可以包含任何数据类型,也可包含另一个列表【可任意组合嵌套】列表是以方括号“[]”包围的数据集合,不同成员以“,”分隔列表可通过序号访问其中成员
定义
>>> l = [] #空列表>>> l = [1,2,3]>>> l = [1,2,3,['a','b']]>>> l = list('linuxeye')>>> l['l', 'i', 'n', 'u', 'x', 'e', 'y', 'e']>>> l = list(range(5))>>> l[0, 1, 2, 3, 4]>>> l = '1;2;3;4;5'.split(';')>>> l['1', '2', '3', '4', '5']
内建函数list(a_sequence) 可以将一个序列转为列表
索引
正索引是编号是从左到右,0开始;负索引编号是从右往左,-1、-2 …;取范围值都是从左至右
>>> LanguageList = ['Python','Shell','Perl','PHP','java','C',"C++","Lisp"]>>> LanguageList[0] #取第一个值'Python'>>> LanguageList[3] #第四个值'PHP'>>> LanguageList[3:]['PHP', 'java', 'C', 'C++', 'Lisp']>>> LanguageList[:3]['Python', 'Shell', 'Perl']>>> LanguageList[2:5]['Perl', 'PHP', 'java']
>>> LanguageList[-1] #倒数第一个值'Lisp'>>> LanguageList[-2] #倒数第二个值'C++'>>> LanguageList[-5:]['PHP', 'java', 'C', 'C++', 'Lisp']>>> LanguageList[-5:-2]['PHP', 'java', 'C']>>> LanguageList[:-2]['Python', 'Shell', 'Perl', 'PHP', 'java', 'C']
增加元素
>>> LanguageList['Python', 'Shell', 'Perl', 'PHP', 'java', 'C', 'C++', 'Lisp']>>> LanguageList.append('GO')>>> LanguageList['Python', 'Shell', 'Perl', 'PHP', 'java', 'C', 'C++', 'Lisp', 'GO']>>> LanguageList.insert(3,'Python') #往PHP元素前插入>>> LanguageList['Python', 'Shell', 'Perl', 'Python', 'PHP', 'java', 'C', 'C++', 'Lisp', 'GO']>>> LanguageList.extend(['Ruby','C#'])>>> LanguageList['Python', 'Shell', 'Perl', 'Python', 'PHP', 'java', 'C', 'C++', 'Lisp', 'GO', 'Ruby', 'C#']
搜索
>>> LanguageList = ['Python', 'Shell', 'Perl', 'Python', 'PHP', 'java', 'C', 'C++', 'Lisp', 'GO', 'Ruby', 'C#']>>> LanguageList.index('Python')0>>> LanguageList.index('C')6>>> LanguageList.index('c')Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: list.index(x): x not in list>>> 'c' in LanguageListFalse>>> LanguageList.index('Python') #统计一个元素的出现次数2
删除元素
>>> LanguageList = ['Python', 'Shell', 'Perl', 'Python', 'PHP', 'java', 'C', 'C++', 'Lisp', 'GO', 'Ruby', 'C#']>>> LanguageList.remove('C')>>> LanguageList.remove('Python')>>> LanguageList.remove('c')Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: list.remove(x): x not in list>>> LanguageList.pop()'C#'>>> LanguageList['Shell', 'Perl', 'Python', 'PHP', 'java', 'C++', 'Lisp', 'GO', 'Ruby']>>> LanguageList.pop(-2)['Shell', 'Perl', 'Python', 'PHP', 'java', 'C++', 'Lisp', 'Ruby']>>> del LanguageList[-3:-1]>>> LanguageList['Shell', 'Perl', 'Python', 'PHP', 'java', 'Ruby']
新闻热点
疑难解答