自学内容网 自学内容网

数据容器-序列-集合-Python

师从黑马程序员

序列

序列的常用操作-切片

切片:从一个序列中,取出一个子序列

语法:序列[起始下标:结束下标,步长]

注:此操作不会影响序列本身,而是会得到一个新的序列

my_list=[0.1,2,3,4,5,6]
result1=my_list[1:4]  #步长默认是1,所以可以省略不写
print(f"结果1:{result1}")#1,2,3

my_tuple=(0,1,2,3,4,5,6)
result2=my_tuple[:]#起始和结束不写表示从头到尾,步长为1可以省略
print(f"结果2:{result2}")

my_str="01234567"
result3=my_str[::2]
print(f"结果3:{result3}")

my_str="01234567"
result4=my_str[::-1]
print(f"结果4:{result4}")

my_list=[0.1,2,3,4,5,6]
result5=my_list[3:1:-1]
print(f"结果5:{result5}")

my_tuple=(0,1,2,3,4,5,6)
result6=my_tuple[::-2]
print(f"结果2:{result6}")

切片实践案例:

my_str="万过薪月,员序程马黑来,nohtyP学"

#方法1
result1=my_str[::-1][9:14]
print(f"方式1结果:{result1}")

#方法2
result2=my_str[5:10][::-1]
print(f"方式2结果:{result2}")

#方法3
result3=my_str.split(",")[1].replace("来","")[::-1]
print(f"方式3结果:{result3}")
my_str="万过薪月,员序程马黑来,nohtyP学"

集合的定义和操作

集合主要特点:不支持重复元素,有去重功能

基本语法:

注:集合无序,集合不支持下标索引访问

添加新元素

移除元素

#定义集合
my_set={"传智教育","黑马程序员","itheima","传智教育","黑马程序员","itheima","传智教育","黑马程序员","itheima"}
my_set.remove("黑马程序员")
print(f"移除元素后,结果:{my_set}")

从集合中随机取出元素

my_set={"传智教育","黑马程序员","itheima","传智教育","黑马程序员","itheima","传智教育","黑马程序员","itheima"}
element=my_set.pop()
print(f"集合取出元素是:{element},取出元素后:{my_set}")

清空集合

my_set={"传智教育","黑马程序员","itheima","传智教育","黑马程序员","itheima","传智教育","黑马程序员","itheima"}
my_set.clear()
print(F"集合被清空后,结果是:{my_set}")

取两个集合的差集

set1={1,2,3}
set2={1,5,6}
set3=set1.difference(set2)
print(f"取差集的结果:{set3}")
print(f"取差集后,所有set1的内容:{set1}")

消除两个集合的差集

set1={1,2,3}
set2={1,5,6}
set1.difference_update(set2)
print(f"消除差集后,所有set1的内容:{set1}")
print(f"消除差集后,所有set2的内容:{set2}")

两个集合合并

set1={1,2,3}
set2={1,5,6}
set3=set1.union(set2)
print(f"2集合合并结果:{set3}")
print(f"合并后集合1:{set1}")
print(f"合并后集合2:{set2}")

统计集合元素数量

set1={1,2,3,4,5,1,2,3,4,5}
num=len(set1)
print(f"集合内的元素数量有:{num}")#5

遍历集合

注:不支持while循环遍历集合

set1={1,2,3,4,5}
for element in set1:
    print(f"集合的元素有:{element}")

 集合常用功能总结

r

my_list=["黑马程序员","传智播客","黑马程序员","传智播客","itheima","itcast","itheima","itcast","best"]

my_set=set()
for element in my_list:
    my_set.add(element)
print(f"集合中有元素:{my_set}")

若有侵权,请联系作者


原文地址:https://blog.csdn.net/axzy5863/article/details/136921177

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!