1.创建集合
1.1 set({ }) 方法:
set1 = set({1,2, "marry"})
1.2 { } 方法:
set2 = {1,2, "marry"}
2. 向集合里增加数据
2.1 add( )添加一条数据或者元组
(列表和字典不能被添加)
2.1.1 增加数据
set1={" 123", 235,”但是”,"张三”,”sddda" }
set1. add("你好")
print (set1)
2.1.2 增加元组
set1={"123",235,”但是”,"张三","sddda"}
set1. add(("你好","你好111"))
print (set1)
2.2 update( ) 迭代着增加
set1={"123",235,"但是","张三","sddda"}
set1. update("a")
print (set1)
set1. update("谭老师")
print (set1)
set1. update([1,2,3])
print (set1)
3.集合的删除
3.1 remove( ) 删除一个元素
[有就直接删除,没有就报错 ]
set1={"123",235,'但是','张三',"sddda"}
set1. remove('123')
print (set1)
3.2 pop( )随机删除一个元素
set1={"123",235,"但是","张三","sddda"}
set1. pop()
print (set1)
3.3 clear ()清空集合
set1={"123",235,"但是","张三","sddda"}
set1. clear ()
print (set1)
4. 集合的重要作用
实现列表中重复元素的去重
1i=[1,2,3,3,3]
print(1i)
1i2=list (set(1i))
print (1i2)
5.enumerate : 枚举
enumerate:枚举,对于一个可迭代的(iterable) /可遍历的对象(如列表、字符串) 组成个一索引序列,利用它可以同时获得索引和值。
例子一:(直接获得索引值和对应位置,返回值是元组)
li=["asf","Asvsb",231,"545","你好"]
for i in enumerate (li):
print(i)
(0,"asf")
(1,"Asvsb")
(2,231)
(3,"545")
(4,"你好")
例子二:(返回一一对应)
li=["asf","Asvsb",231,"545","你好"]
for key,value in enumerate (li):
print(key,value)
0 asf
1 Asvsb
2 231
3 545
4 你好
例子三:(第二个参数是索引值开始的位置,起始位置是0,可以修改)
li=["asf","Asvsb",231,"545","你好"]
for index,name in enumerate (li,3):
print(index,name)
3 asf
4 Asvsb
5 231
6 545
7 你好
|