python集合set练习题
时间: 2023-11-23 21:57:37 浏览: 349
以下是Python集合set的一些练习题:
1. 创建一个新的空集
```python
set1 = set()
```
2. 迭代集合
```python
set2 = {"apple", "banana", "cherry"}
for x in set2:
print(x)
```
3. 在集合中添加成员
```python
set3 = {"apple", "banana", "cherry"}
set3.add("orange")
print(set3)
```
4. 从Python集合中删除成员
```python
set4 = {"apple", "banana", "cherry"}
set4.remove("banana")
print(set4)
```
5. 存在则从该集合中删除该成员
```python
set5 = {"apple", "banana", "cherry"}
set5.discard("banana")
print(set5)
```
6. 集合的交集
```python
set6a = {1, 2, 3}
set6b = {2, 3, 4}
set6c = set6a.intersection(set6b)
print(set6c)
```
7. 集合的并集
```python
set7a = {1, 2, 3}
set7b = {2, 3, 4}
set7c = set7a.union(set7b)
print(set7c)
```
8. 创建集合差异
```python
set8a = {1, 2, 3}
set8b = {2, 3, 4}
set8c = set8a.difference(set8b)
print(set8c)
```
9. 检查一个集合是否是另一个集合的子集
```python
set9a = {1, 2, 3}
set9b = {2, 3}
set9c = set9b.issubset(set9a)
print(set9c)
```
10. 从给定的集合中删除所有元素
```python
set10 = {"Red", "Green", "Black", "White"}
set10.clear()
print(set10)
```
11. 在一个集合中查找最大值和最小值
```python
set11 = {1, 2, 3, 4, 5}
max_value = max(set11)
min_value = min(set11)
print("Max value in set: ", max_value)
print("Min value in set: ", min_value)
```
12. 查找集合的长度
```python
set12 = {1, 2, 3, 4, 5}
length = len(set12)
print("Length of set: ", length)
```
13. 检查给定值是否存在于集合中
```python
set13 = {1, 2, 3, 4, 5}
value = 3
if value in set13:
print("Value exists in set")
else:
print("Value does not exist in set")
```
14. 检查两个给定的集合是否没有共同的元素
```python
set14a = {1, 2, 3}
set14b = {4, 5, 6}
set14c = set14a.isdisjoint(set14b)
print(set14c)
```
15. 从第一组中删除第二组的交集
```python
set15a = {1, 2, 3}
set15b = {2, 3, 4}
set15a.difference_update(set15b)
print(set15a)
```
阅读全文