黑马程序员技术交流社区

标题: 列表相关的总结 [打印本页]

作者: hz李振    时间: 2018-5-31 21:39
标题: 列表相关的总结
列表的创建列表可以储存多种不同数据类型的组合
l = [[1,2,2],3,'hello',2e+3,3j+9,True]print(l,type(l))列表的特性索引l = [[1,3,2],3,'hello',2e+3,3j+9,True]print(l[0])    #[1, 3, 2]print(l[-1])   #Trueprint(l[0][1]) #2  嵌套列表的索引强制转换range(5)的值为列表
l = list(range(5))print(l)切片l = [[1,2,2],3,'hello',2e+3,3j+9,True]print(l[1:3])   #[3, 'hello']print(l[:-1])   #[[1, 2, 2], 3, 'hello', 2000.0, (9+3j)]:除了最后一个的其他print(l[1:])    #[3, 'hello', 2000.0, (9+3j), True] #除了第一个的所有索引print(l[::-1])  #[True, (9+3j), 2000.0, 'hello', 3, [1, 2, 2]] #反转列表print(l[::2])   #[[1, 2, 2], 'hello', (9+3j)]重复l = [1,2,3]print(l*2)  #[1, 2, 3, 1, 2, 3]连接l = [1,2,3]l1 = [4,5,6]print(l+l1) #[1, 2, 3, 4, 5, 6]成员符操作l = [1,2,3]print(1 in l) #Trueprint(1 not in l) #Falsefor循环l = [1,2,3]for i in l:    print(i)  #输出1 2 3列表切片的练习
假定有下面这样的列表:
names = [‘fentiao’, ‘fendai’, ‘fensi’, ‘apple’]
输出结果为:’I have fentiao, fendai, fensi and apple.’
names = ['fentiao', 'fendai', 'fensi', 'apple']print('i have '+",".join(names[:-1])+' and '+names[-1])#i have fentiao,fendai,fensi and apple列表的增加append #追加元素到列表最后
languages = ['shell', 'c', 'python']languages.append('C++')print(languages.append('c++'))  # Noneprint(languages)  # ['shell', 'c', 'python', 'C++', 'c++']languages = ['shell', 'c', 'python']other = ['java','Go']languages.append(other)print(languages) #['shell', 'c', 'python', ['java', 'Go']]extend #追加多个元素到列表中
languages = ['shell', 'c', 'python']other = ['java','Go']languages.extend(other)print(languages)  #['shell', 'c', 'python', 'java', 'Go']inster #添加元素到指定的索引前面
languages = ['shell', 'c', 'python']languages.insert(0,'java')print(languages) #['java', 'shell', 'c', 'python']列表的删除clear #清空列表
languages = ['shell', 'c', 'python']languages.clear()print(languages) #[]pop #弹出 删除指定索引的值,默认情况下删除最后一个
languages = ['shell', 'c', 'python']a = languages.pop()print(languages,a)  #['shell', 'c'] pythonremove # 删除指定的值
languages = ['shell', 'c', 'python']languages.remove('shell')print(languages)   #['c', 'python']del # 删除列表元素可以通过索引和切片的方式删除
languages = ['shell', 'c', 'python']del languages[:-1]   # ['python']del languages[2]     # ['shell','c']print(languages)列表取重的方法l = ['shell', 'c', 'python', 'shell', 'c', 'C#']new_l = []for i in l:    if i not in new_l and l.count(i) == 1:        new_l.append(i)print(new_l)修改元素列表通过索引修改
l = ['shell', 'c', 'python', 'shell', 'c', 'C#']l[0] = 'php'print(l)   #['php', 'c', 'python', 'shell', 'c', 'C#']通过切片修改
l = ['shell', 'c', 'python', 'shell', 'c', 'C#']l[:2] = 'php','java'print(l) #['php', 'java', 'python', 'shell', 'c', 'C#']列表的一些其他用法
languages = ['shell', 'c', 'python', 'shell', 'a', 'B', 'c']print(languages.count('shell'))  #列表中,元素出现的次数print(languages.index('shell',1,4)) #在1-4之间第一次出现shell的索引值该方式不能实现复制, 因为两个变量指向同一块内存空间;
languages1 = languages






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2