1 集合(Set)
thisset = {"apple", "banana", "cherry"}print(thisset) # {'cherry', 'apple', 'banana'}
2 访问元素
thisset = {"apple", "banana", "cherry"}for x in thisset:print(x)
thisset = {"apple", "banana", "cherry"}print("banana" in thisset) # True
3 更改元素
4 添加元素
thisset = {"apple", "banana", "cherry"}thisset.add("orange")print(thisset) # {'cherry', 'apple', 'orange', 'banana'}
thisset = {"apple", "banana", "cherry"}thisset.update(["orange", "mango", "grapes"])print(thisset) # {'cherry', 'mango', 'grapes', 'apple', 'orange', 'banana'}
5 获取 Set 的长度
thisset = {"apple", "banana", "cherry"}print(len(thisset)) # 3
6 删除项目
thisset = {"apple", "banana", "cherry"}thisset.remove("banana")print(thisset) # {'cherry', 'apple'}
thisset = {"apple", "banana", "cherry"}thisset.discard("banana")print(thisset) # {'cherry', 'apple'}
thisset = {"apple", "banana", "cherry"}x = thisset.pop()print(x) # 'cherry'print(thisset) # {'apple', 'banana'}
thisset = {"apple", "banana", "cherry"}thisset.clear()print(thisset) # set()
thisset = {"apple", "banana", "cherry"}del thissetprint(thisset) # 报错
7 合并两个集合
set1 = {“a”, “b” , “c”}set2 = {1, 2, 3}set3 = set1.union(set2)print(set3) # {1, ‘c’, 2, 3, ‘a’, ‘b’}
set1 = {"a", "b" , "c"}set2 = {1, 2, 3}set1.update(set2)print(set1) # {1, 'c', 2, 3, 'a', 'b'}
8 set() 构造函数
thisset = set(("apple", "banana", "cherry")) # 请留意这个双括号print(thisset) # {'cherry', 'apple', 'banana'}
9 Set 方法
| 方法 | 描述 |
|---|---|
| add() | 向集合添加元素。 |
| clear() | 删除集合中的所有元素。 |
| copy() | 返回集合的副本。 |
| difference() | 返回包含两个或更多集合之间差异的集合。 |
| difference_update() | 删除此集合中也包含在另一个指定集合中的项目。 |
| discard() | 删除指定项目。 |
| intersection() | 返回为两个其他集合的交集的集合。 |
| intersection_update() | 删除此集合中不存在于其他指定集合中的项目。 |
| isdisjoint() | 返回两个集合是否有交集。 |
| issubset() | 返回另一个集合是否包含此集合。 |
| issuperset() | 返回此集合是否包含另一个集合。 |
| pop() | 从集合中删除一个元素。 |
| remove() | 删除指定元素。 |
| symmetric_difference() | 返回具有两组集合的对称差集的集合。 |
| symmetric_difference_update() | 插入此集合和另一个集合的对称差集。 |
| union() | 返回包含集合并集的集合。 |
| update() | 用此集合和其他集合的并集来更新集合。 |
https://blog.csdn.net/weixin_44237659?spm=1011.2124.3001.5343
文章转载自微思研,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




