Data container for basic learning in python: set (set)

Data container: set (collection)

Lists can be modified, support repeated elements, and are ordered
. Tuples and strings cannot be modified, support repeated elements, and are ordered.

The limitation is: they all support repeated elements.

The main feature of a collection is that it does not support duplication of elements (it has its own deduplication function), and its content is unordered .

Definition of set

Basic syntax:

Define a collection variable: variable name = {element, element, ..., element}
Define an empty collection: variable name = set()

Basically the same definitions as lists, tuples, strings, etc.:

List usage: []
Tuple usage: ()
String usage: ""
Set usage: {}

Note: Collections are automatically deduplicated and unordered.

Example:

# 定义集合
my_set = {
    
    "my", "you", "ergou", "二狗", "ergou"}
my_set_empty = set()  # 定义空集合
print(f"my_set的内容是{
      
      my_set},类型是:{
      
      type(my_set)}")
print(f"my_set_empty的内容是{
      
      my_set_empty},类型是:{
      
      type(my_set_empty)}")

Operation result:
The content of my_set is {'ergou', 'you', 'ergou', 'my'}, the type is: <class 'set'> The content of
my_set_empty is set(), the type is: <class 'set '>

Common operations on collections – modification

Because sets are unordered , the setSubscript index access is not supported,
but sets, like lists, are allowed to be modified , so let’s take a look at how to modify sets.

Add new element

Syntax: collection.add(element). Add the specified element to the collection.
Result: The collection itself is modified and new elements are added.

Remove element

Syntax: Collection.remove(element), removes the specified element from the collection.
Result: The collection itself is modified and the element is removed.

Randomly remove elements from the set

Syntax: Set.pop(), function, randomly remove an element from the set.
Result: You will get the result of one element. At the same time the collection itself is modified and elements are removed

Clear collection

Syntax: collection.clear(), function, clears the collection
Result: The collection itself is cleared

Get the difference between 2 sets

Syntax: set 1.difference (set 2), function: take out the difference between set 1 and set 2 (set 1 has it but set 2 does not) Result:
get a new set, set 1 and set 2 remain unchanged

Eliminate the difference between two sets

Syntax: Set 1.difference_update (set 2)
Function: Compare set 1 and set 2. In set 1, delete the same elements as set 2.
Result: Set 1 is modified, set 2 remains unchanged

2 sets merged

Syntax: Set 1.union (set 2)
Function: Combine set 1 and set 2 into a new set
Result: Get a new set, set 1 and set 2 remain unchanged

Example:

my_set = {
    
    "my", "you", "ergou", "二狗", "ergou"}
# 添加新元素
my_set.add("python")
my_set.add("学习")
print(f"my_set条件元素后的内容是{
      
      my_set}")

# 移除元素
my_set.remove("you")
print(f"my_set移除元素后的内容是{
      
      my_set}")

# 随机取出一个元素
my_set = {
    
    "my", "you", "ergou", "二狗", "ergou"}
element = my_set.pop()
print(f"my_set集合被随机取出的元素是:{
      
      element},取出元素后的内容是{
      
      my_set}")

# 清空集合,clear
my_set.clear()
print(f"my_set清空后的内容是{
      
      my_set}")

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

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

# 2个集合合并为1个
set1 = {
    
    1, 2, 3}
set2 = {
    
    1, 5, 6}
set3 = set1.union(set2)
print(f"2个集合合并后的结果是:{
      
      set3}")
print(f"合并后set1的内容:{
      
      set1}")
print(f"合并后set2的内容:{
      
      set2}")

operation result:

The content after the conditional element of my_set is {'python', 'ergou', 'you', 'my', 'ergou', 'learning'} The content of my_set after the element is removed is {'python', 'ergou'
, 'my', 'Ergou', 'Learning'}
The element randomly taken out of the my_set set is: ergou, and the content after the element is taken out is {'you', 'Ergou', 'my'} The content after my_set is cleared
is
The result after set() takes out the difference set is: {2, 3}
After taking the difference set, the original content of set1: {1, 2, 3}
After taking the difference set, the original content of set2: {1, 5, 6}
After eliminating the difference set, the content of set1: {2, 3}
After eliminating the difference set, the content of set2: {1, 5, 6}
The result after merging the two sets is: {1, 2, 3, 5, 6}
The contents of set1 after merging: {1, 2, 3}
The contents of set2 after merging: {1, 5, 6}

Common operations on sets - set length

Check the number of elements in a collection

Syntax: len (set)
Function: Count how many elements there are in the set
Result: Get an integer result

Example:

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

operation result:

The number of elements in the set is: 5

Common operations on collections - for loop traversal

Collections also support for loop traversal.
Note: Collections do not support subscript indexing , so while loops are not supported .

Example:

# 集合的遍历
# 集合不支持下标索引,不能用while循环
# 可以用for循环
set1 = {
    
    1, 2, 3, 4, 5}
for element in set1:
    print(f"集合的元素有:{
      
      element}")

Operation result:
The elements of the set are: 1
The elements of the set are: 2
The elements of the set are: 3
The elements of the set are: 4
The elements of the set are: 5

Summary of commonly used functions of collections

serial number operate illustrate
1 collection.add(element) Add an element to the collection
2 collection.remove(element) Removes the specified element from the collection
3 collection.pop() Randomly remove an element from the set
4 set.clear() Clear the collection
5 Set1.difference(set2) Get a new set, which contains the difference set of the two sets. The contents of the original two sets remain unchanged.
6 set 1.difference_update(set 2) In set 1, delete the elements that exist in set 2, set 1 is modified, and set 2 remains unchanged.
7 Set1.union(set2) Get a new set containing all the elements of the two sets, and the contents of the original two sets remain unchanged.
8 len(set) Get an integer that records the number of elements in the set

Collection features

1. Can accommodate multiple data
2. Can accommodate different types of data (mixed)
3. The data isdisorderStored (subscript index is not supported)
4.Duplication is not allowedThe data exists
5. It can be modified (adding or deleting elements, etc.)
6. It supports for loops but does not support while loops because subscript indexes are not supported.

Collection exercise - information deduplication

Existing list: my_list = ['ergou', 'ergou', 'er', 'ergou', 'I', 'ergou']
Please:
① Define an empty collection
② Traverse the list through a for loop
③ In the for loop Add the elements of the list to the collection
④ Finally get the collection object after deduplicating the elements and print it out

my_list = ['二狗', 'ergou', 'er', 'ergou', '我', '二狗']
# 定义一个空集合
my_set = set()

# 通过for循环遍历列表
for element in my_list:
    # 在for循环中将列表的元素添加至集合
    my_set.add(element)

# 最终得到元素去重后的集合对象,并打印输出
print(f"列表的内容是:{
      
      my_list}")
print(f"通过for循环后,得到的集合对象是:{
      
      my_set}")

operation result:

The content of the list is: ['ergou', 'ergou', 'er', 'ergou', 'I', 'ERGOU'] After passing through the for loop, the collection object obtained is: {'I', 'ERGOU
' dog', 'ergou', 'er'}

Guess you like

Origin blog.csdn.net/weixin_44996886/article/details/132678446
Recommended