列表list:
用途:用来存放多个值
定义方式:定义在[]中括号内,用逗号分隔开多个值,值可以是任意类型
类型转换: 但凡能被for循环遍历的数据类型都可以传给list()转换成列表类型,list()会跟for循环一样遍历出数据类型中包含的每一个元素然后放到列表中 >>> list('wdad') # 结果:['w', 'd', 'a', 'd'] >>> list([1,2,3]) # 结果:[1, 2, 3] >>> list({"name":"jason","age":18}) #结果:['name', 'age'] >>> list((1,2,3)) # 结果:[1, 2, 3] >>> list({1,2,3,4}) # 结果:[1, 2, 3, 4]
常用操作: #1、索引取值:(正反都可以取,即可存也可取) user_info = ['egon',18,['football','eat','sleep']] print(user_info[2][0]) >>> football #2、索引切片 my_friends = ['tony', 'jason', 'tom', 4] print(my_friends[0:4:2]) #第三个参数2代表步长 >>>['tony', 'tom'] #3、长度len(): 获取列表中元素的个数 my_friends = ['tony', 'jason', 'tom', 4] len(my_friends) >>>4 #4、成员运算in和not in my_friends = ['tony', 'jason', 'tom', 4] 'tony' in my_friends >>>True 'egon' in my_friends >>>False #5、循环 # 循环遍历my_friends列表里面的值 for i in my_friends: print(i) 'tony' 'jack' 'jason' 4 内置方法: #1、添加 # append(): 列表尾部追加值,一次性只能添加一个值 l1 = ['a','b','c'] l1.append('d') print(l1) >>>['a', 'b', 'c', 'd'] # insert(): 插入值,通过索引指定插入的位置 l1 = ['a','b','c'] l1.insert(0,"first") # 0表示按索引位置插值 print(l1) >>>['first', 'a', 'b', 'c'] # extend(): 一次性在列表尾部添加多个元素 l1 = ['a','b','c'] l1.extend(['a','b','c']) print(l1) >>>['a', 'b', 'c', 'a', 'b', 'c'] #2、删除 #2.1 remove():删除指定值,只能删一个,没有返回值 l = [11,22,33,22,44] res=l.remove(22) # 从左往右查找第一个括号内需要删除的元素 print(res) >>>None #2.2 pop()默认从列表最后一个元素开始删,并将删除的值返回,括号内可以通过加索引值来指定删除元素 l = [11,22,33,22,44] res=l.pop() print(res) >>>44 res=l.pop(1) print(res) >>>22 #2.3 del 彻底删除 l = [11,22,33,44] del l[2] # 删除索引为2的元素 print(l) >>>[11,22,44] #3、reverse()颠倒列表内元素顺序 l = [11,22,33,44] l.reverse() print(l) >>>[44,33,22,11] #4、sort()给列表内所有元素排序 # 4.1 排序时列表元素之间必须是相同数据类型,不可混搭,否则报错 l = [11,22,3,42,7,55] l.sort() print(l) >>>[3, 7, 11, 22, 42, 55] # 默认从小到大排序 l = [11,22,3,42,7,55] l.sort(reverse=True) # reverse用来指定是否跌倒排序,默认为False print(l) >>> [55, 42, 22, 11, 7, 3] #5、sorted():python的内置函数,在排序时生成一个新列表,原数据不变 #6、count():统计当前列表内指定元素的个数 l = [11,22,3,42,7,55,11] print(l.count(11)) >>>2 #7、index():获取当前指定元素的索引值,还可以指定查找范围 l = [11,22,3,42,7,55,11] print(l.index(11,1,7)) >>>6 #8、clear():清空列表数据 l = [11,22,3,42,7,55,11] l.clear() print(l) >>>[] 补充知识点: #队列:先进先出 l1 =[] l1.append(1) l1.append(2) l1.append(3) print(l1) l1.pop(0) print(l1) l1.pop(0) l1.pop(0) print(l1) #堆栈:先进后出 l1 =[] l1.append(1) l1.append(2) l1.append(3) print(l1) l1.pop() print(l1) l1.pop() l1.pop() print(l1)