join
s = 'abcdefghigk' s1 = '-'.join(s) print(s1) #结果:a-b-c-d-e-f-g-h-i-g-k
list操作
列表里可以存储所有数据类型 int.str.boor.[].().{}
切片,索引与字符串一样(不改变原数据类型)
增:①append 在最后加
list = ["a","b","c","d","e","f","g",1,2,3] list.append("qqq") print(list) #在后面加,结果为:['a', 'b', 'c', 'd', 'e', 'f', 'g', 1, 2, 3, 'qqq']
②insert 插入
list = ["a","b","c","d","e","f","g",1,2,3] list.insert(3,'X') print(list) #3:索引 #结果:['a', 'b', 'c', 'X', 'd', 'e', 'f', 'g', 1, 2, 3]
③extend 迭代插入
list = ["a","b","c","d","e","f","g",1,2,3] list.extend('我是你爸爸') list.extend([1,2,33,4]) print(list) #结果:['a', 'b', 'c', 'd', 'e', 'f', 'g', 1, 2, 3, '我', '是', '你', '爸', '爸', 1, 2, 33, 4] #把所有内容拆开,挨个插入
删除
①pop 按索引删除,有返回值
list = ["a","b","c","d","e","f","g",1,2,3] list.pop(2)
ret = list.pop(2) print(list)
print(ret) #结果:['a', 'b', 'd', 'e', 'f', 'g', 1, 2, 3]
# c
②remove 按元素删除
list = ["a","b","c","d","e","f","g",1,2,3] list.remove('b') print(list) #结果:['a', 'c', 'd', 'e', 'f', 'g', 1, 2, 3]
③clear清空列表
list = ["a","b","c","d","e","f","g",1,2,3] list.clear() print(list) #清空所有数据,但保留[] #输出:[]
④del 删除列表
#功能一:删除列表 list = ["a","b","c","d","e","f","g",1,2,3] del list print(list)
功能二:按照索引,切片去删除: list = ["a","b","c","d","e","f","g",1,2,3] del list[0] #删除第一个字母 print(list) del list[0:3] #删除前四个 print(list) del list[1:6:2] #2为步长 print(list) #结果:['a', 'c', 'e', 'g', 1, 2, 3]
改
#按照索引改 list = ["a","b","c","d","e","f","g",1,2,3] list[0]="aaa" print(list) #结果:['aaa', 'b', 'c', 'd', 'e', 'f', 'g', 1, 2, 3]
#按照切片改 (按照迭代) li = ["a","b","c","d"] li[2:3] = "python" print(li) #结果:['a', 'b', 'p', 'y', 't', 'h', 'o', 'n', 'd']
查
l1 = ["a","b","c","d"] print(l1[1]) print(l1[1:3]) #结果:b ['b', 'c']
#循环查 for i in l1: print(i)
公共方法
len:长度 l1 = ["a","b","c","d"] print(len(l1)) #输出:4 count:元素出现次数 l1 = ["a","a","a","b","c","d"] print(l1.count("a")) #输出:3 index:通过元素找索引,可以切片 l1 = ["a","b","c","d"] print(l1.index('d')) #输出3
sort排序,从小到大:
l1 = [1,3,6,9,8,4,7,2] l1.sort() print(l1) #输出:1,2,3,4,5,6,7,8,9
从大到小:
l1 = [1,3,6,9,8,4,7,2] l1.sort(reverse = True) print(l1) #输出:9,8,7,6,5,4,3,2,1
倒叙:从后往前打印
l1 = [1,3,6,9,8,4,7,2] l1.reverse() print(l1) #结果:[2, 7, 4, 8, 9, 6, 3, 1]
列表嵌套:
l1 = ['a','b','c',['d','e'],1,2,3] l1[3][0] ="X" #选中的是‘d' print(l1) #输出:['a', 'b', 'c', ['X', 'e'], 1, 2, 3]
元组:只能读不能改
如果元组里面有列表,列表可以改
l1 = ('a','b','c',['d','e'],1,2,3) l1[3][0] = "X" print(l1) #输出:('a', 'b', 'c', ['X', 'e'], 1, 2, 3)
range 范围:
里面的元素是数字,且可控,一般与for配合使用,有步长
for i in range(1,10): print(i) #输出 1,2.....8,9 for i in range(11): print(i) #输出 0,1,2....10 for i in range(1,10,2): #2是步长 print(i) #输出: [1,3,5,7,9] for i in range(10, 0, -2): print(i) #输出: 10,8,6,4,2 #从后往前 步长为2
把列表里的列表拆开打印:
l1 = [1,2,3,'abc',[2,3,'qwe'],7] for i in l1: if type(i) == list: for j in i: print(j) else: print(i) #输出: 1 2 3 abc 2 3 qwe 7