Python学习------第十一天
了解序列以及序列的切片操作
切片:从一个序列中取出一个子序列(字符串,列表,元组均支持)
#对序列进行切片操作 mylist = [0,1,2,3,4,5,6] result = mylist[1:4] print(result) #对元组进行切片 myturple = (0,1,2,3,4,5,6) result2 = myturple[:] result3 = myturple[0:5] print(result2) print(result3) #对str进行切片,从头开始,步长为2 mystr = "01234567" result4 = mystr[::2] print(result4) #对字符串进行切片从头开始到最后结束,步长为-1 #相当于反转 mystr1 = "01234567" result5 = mystr1[::-1] print(result5) #对列表进行切片从3开始到1结束,步长为-1 mylist = [0,1,2,3,4,5,6,7] result = mylist[3:1:-1] print(result) #对元组进行切片,头开始到尾结束步长为-2 myturple = (0,1,2,3,4,5,6) result = myturple[::-2] print(result)
#序列的切片实践 mystr = "万过薪月,员序程马黑来,nohtyP学" result1 = mystr[::-1] result = result1[9:14] print(result)mystr = "万过薪月,员序程马黑来,nohtyP学" result = mystr.split(",")[1][::-1][1::] print(result)mystr = "万过薪月,员序程马黑来,nohtyP学" result = mystr.split(",")[1].replace("来","")[::-1] print(result)mystr = "万过薪月,员序程马黑来,nohtyP学" result = mystr[5:10:][::-1] print(result)
2.set集合 {}
不支持元素的重复
#定义集合 my_set = {"itheima","itcast","itheima","itcast"} empty_set = set()
#集合学习 #定义集合 my_set = {"itheima","itcast","itheima","itcast"} empty_set = set() #添加元素 my_set.add("Python") #移除元素 # my_set.remove("itheima") #随机取出一个元素 element = my_set.pop() print(my_set,element) #清空集合 my_set.clear() print(my_set)#取2个集合的差集 set1 = {1,2,3} set2 = {1,4,5} set3 = set1.difference(set2) set4 = set2.difference(set1) set5 = set3.difference(set4) print(set1) print(set2) print(set3) print(set4) print(set5) """ #消除集合1中和集合2相同的元素 set1 = {1,2,3} set2 = {1,4,5} set1.difference_update(set2) print(set1) set1 = {1,2,3} set2 = {1,4,5} set2.difference_update(set1) print(set2) #合并两个集合 union set3 = set1.union(set2) print(set3) #统计集合数量 #集合是去重的 set1={1,2,3,4,5,6,7,89,1,1,1} number = len(set1) print(number) #集合的遍历 #不支持while循环,不支持下标索引 #支持for循环 set1={1,2,3,4,5,6,7,89,1,1,1} for element in set1:print(element)