# 总算把集合玩明白了！

### difference(set)

set_1.difference(set_2) ：这个方法帮助你获得两个集合之间的差异，换句话说，它让你获得存在于set_1中而不存在于给定集合（set_2）中的元素。

``````# example 1
recepie_requirements = {'orange', 'chocolate', 'salt', 'pepper'}
what_I_have = {'apple', 'banana','salt'}
# I have to buy orange chocolate pepper

# example2
all_subscribers = {"aya", "john", "smith", "sparf", "kyle"}
# {'kyle', 'smith', 'john'}
print(users)``````

### union(set)

set_1.union(set_2) ：(set_1 U set_2) 这个set方法返回一个包含set_1的元素和set_2的元素的集合，此外，返回的集合只包含唯一的元素。

``````admins = {'aya', 'sparf'}
users = {'aya','kyle', 'smith', 'john'}

# {'smith', 'aya', 'sparf', 'kyle', 'john'}
print(all_subscribers)``````

### intersection(set)

set_1.intersection(set_2) ：取两个集合的交集，只返回同时存在于set_1和set_2中的元素。

``````shop = {'orange', 'pepper', 'banana', 'sugar'}
what_I_have = {'orange', 'sugar'}

# I should not buy {'orange', 'sugar'} because I have them!
print(f'I should not buy {shop.intersection(what_I_have)} because I have them!')``````

### issubset()

set_1.issubset(set_2) ：检查set_1的所有元素是否存在于set_2中。

``````nearest_library_books = {"the power of now", 'why we sleep', 'rich dad poor dad'}
necessary_books = {'atomic habits','the 48 laws of power', 'why we sleep'}

if necessary_books.issubset(nearest_library_books):
else:
print('unfortunately, you have to go to another library')

# unfortunately, you have to go to another library``````

### issuperset()

set_1.issuperset(set_2) : 检查set_2的所有元素是否存在于set_1中。

``````nearest_library_books = {"the power of now", 'why we sleep', 'rich dad poor dad'}
necessary_books = {'atomic habits','the 48 laws of power', 'why we sleep'}

if nearest_library_books.issuperset(necessary_books):
else:
print('unfortunately, you have to go to another library')

# unfortunately, you have to go to another library``````

### isdisjoint(set)

isdisjoint(set) : 检查这两个集合是否不包含共同的元素。

``````set_1 = {12, 38, 36}
set_2 = {4, 40, 12}
# means can set_1 element - set_2 element == 0 ?
can_substruction_be_zero = set_1.isdisjoint(set_2)
print(can_substruction_be_zero) # False``````

pop() : 从一个集合中删除一个随机元素。

remove(value) : 删除一个集合中的指定元素，如果该元素不存在，则引发错误。

``````users = {"Aya Bouchiha", "John Doe", "Kyle Smith", "Nabo Snay"}
deleted_account = 'Aya Bouchiha'

print(users) # {'Kyle Smith', 'John Doe', 'Nabo Snay'}

users.remove('Kyle Smith')
print(users) # {'Nabo Snay', 'John Doe'}

users.pop()
print(users) # {'John Doe'}

users.remove('Hello!') # KeyError``````

### clear()

clear() : 删除集合中所有元素。

``````countries = {'Morocco', 'UK', 'Spain', 'USA', 'UK'}

print(len(countries)) # 4

countries.clear()

print(countries) # set()
print(len(countries)) # 0``````

### copy

copy() : 这个方法让你得到一个指定元素集的副本

``````countries = {'Morocco', 'UK', 'Spain', 'USA', 'UK'}

print(countries) # {'UK', 'Morocco', 'Spain', 'USA'}
print(countries.copy()) # {'UK', 'Morocco', 'Spain', 'USA'}``````

23 声望
10 粉丝
0 条评论