python list、tuple、set和dict比较(list篇)
一、list、tuple、set和dict图表比较
二、list
1、创建list
L1=[1,2,3,3,'a','python']
L2=[2,1,2,3,4]
L3=['Hello','Python','Nice']
2、list访问
print('L1[0]:',L1[0]) print('L1[2:4]:',L1[2:4]) print('L1[-1]:',L1[-1]) 输出结果为: L1[0]: [1] L1[2:4]: [3,3] L1[-1]: ['python']
3、list更新
L1=[1,2,3,'a','python'] L2=[1,2,3,4,5,6,7,8,9] L1[3]=0 L2[2:5]=[11,13,14]
print(L1) print(L2) 输出结果为: [1, 2, 3, 0, 'python'] [1, 2, 11, 13, 14, 6, 7, 8, 9]
4、list增删——append(),insert(),pop(),remove()
L1=[1,2,3,4]
L2=['A','B',4]
L3=[1,'E','U',0]
L4=['q','w',4,7]
L1.append('hhq') #list.append() 在list末尾增加一个元素
L2.insert(4,1314) #list.insert(index,obj) 在指定位置插入一个元素
L3.pop(2) #list.pop()默认删除最后一个元素,list.pop(index)删除指定元素
L4.remove(7) #list.remove(obj)移除指定元素
Q=L1*3 #list元素重复3次
#list.append() 在list末尾增加一个元素
L2.insert(4,1314) #list.insert(index,obj) 在指定位置插入一个元素
L3.pop(2) #list.pop()默认删除最后一个元素,list.pop(index)删除指定元素
L4.remove(7) #list.remove(obj)移除指定元素
Q=L1*3 #list元素重复3次
print(L1)
print(L2)
print(L3)
print(Q)
输出结果为:
[1, 2, 3, 4, 'hhq']
['B', 4, 1314]
[1, 'E', 0]
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
clear()、del list
L1=[1,2,3,4]
print(L1)
L1.clear() #list.clear()清空列表
print(L1)
输出结果为:
[1, 2, 3, 4]
[]
#list.clear()清空列表
print(L1)
输出结果为:
[1, 2, 3, 4]
[]
5、list排序
reverse()
L1=[1,8,3,4]
L1.reverse() #将列表元素顺序颠倒。
print(L1)
输出结果为:
[4, 3, 8, 1]
#将列表元素顺序颠倒。
print(L1)
输出结果为:
[4, 3, 8, 1]
sort()
l=['q','a','python','u','d','D']
q1=[9,3,6,0,1,6,2]
q2=[9,3,6,0,1,6,2]
l.sort()
q1.sort()
q2.sort(reverse=True) #sort 默认升序,加上reverse=True,直接降序排序
print(l)
print(q1)
print(q2)
输出结果为:
['D', 'a', 'd', 'python', 'q', 'u']
[0, 1, 2, 3, 6, 6, 9]
[9, 6, 6, 3, 2, 1, 0]
#sort 默认升序,加上reverse=True,直接降序排序
print(l)
print(q1)
print(q2)
输出结果为:
['D', 'a', 'd', 'python', 'q', 'u']
[0, 1, 2, 3, 6, 6, 9]
[9, 6, 6, 3, 2, 1, 0]
6、list合并拼接
extend()
L1=[1,2,3,'a','python']
L2=[6,7,8,9]
L1.extend(L2) #list1.extend(list2)把list2的元素加到list1的后面;
print(L1)
print(L2)
输出结果为:
[1, 2, 3, 'a', 'python', 6, 7, 8, 9]
[6, 7, 8, 9]
#list1.extend(list2)把list2的元素加到list1的后面;
print(L1)
print(L2)
输出结果为:
[1, 2, 3, 'a', 'python', 6, 7, 8, 9]
[6, 7, 8, 9]
list=list1+list2
L1=[1,2,3,'a','python']
L2=[6,7,8,9]
L=L1+L2
print(L)
输出结果:
[1, 2, 3, 'a', 'python', 6, 7, 8, 9]
7、删除list中含有指定字符的元素
方法一:使用【not in】
a=['1','2','hi','a.txt','a.rar','你好','qq.txt']
aa=[]
for i in a:
if '.txt' not in i and '.rar' not in i:
aa.append(i)
print(aa)
#输出结果为:
['1', '2', 'hi', '你好']
方法二:使用正则
import re
a=['1','2','hi','a.txt','a.rar','你好','qq.txt']
r=re.compile(r'.rar|.txt')
aa=[i for i in a if not r.findall(i)]
print(aa)
#输出结果为:
['1', '2', 'hi', '你好']
8、list其余操作函数
1、len(list):列表元素个数
2、max(list):返回列表元素最大值
3、min(list):返回列表元素最小值
4、list(seq):将元组转换为列表
5、enumerate:打印元素对应的下标和元素
6、切片:
name[n:m] 切片不包含m的值(顾头不顾尾)
name[:m] 若切片前面值缺省,从初始值开始取
name[n:] 若切片后面的值缺省,取到末尾值
name[:] 若全部缺省,则取全部
name[n:m:s] s:步长 隔多少个元素取一次
步长是正数,从左往右取
步长是负数,从右往左取
注:切片同样适用于字符串,字符串也有下标