[Python] sequence type ③-collection

1. Introduction to set

A collection is a 无序可变kind of container object.
The biggest feature of a collection is that the elements in the same collection are unique 不允许有重复, so the collection has its own "deduplication" effect

2. Definition of set

There are two ways to define a collection:

  • Use {} for definition, this way 不能定义空集合.
  • Use set() to define

Example 1:

a = {
    
    }
b = set()
print(type(a))
print(type(b))

Run the screenshot:
insert image description here
You can see that although the code does not report an error, the result is different. The type of a is a dictionary type, and the type of b is a collection type. This is a place that needs attention.如果想要定义一个空集合,只能使用set()的方式进行定义.

Because the elements in the collection cannot be repeated, the collection has the function of automatic deduplication.
Example 2:

# 自动去重
a = {
    
    1, "python", 2.3, 1, "python", 2.3, 1, "python", 2.3, "python"}
print(a)
print(type(a))

# 输出结果:
# {1, 2.3, 'python'}
# <class 'set'>

The collection is unordered . Note the order of the output above, although "python" is before 2.3, but 2.3 is before "python" in the output.

集合是不支持下标索引访问Therefore collections do not have slicing operations either.

3. Collection traversal

Although the collection does not support subscript index access, it can be traversed with a for loop

Syntax: for temporary traversal in collection:

a = {
    
    1, "python", 2.3}
for elem in a:
    print(elem)
 
# 1
# 2.3
# python

4. Common methods of collection

Here are some common methods of collections:

method describe
collection.add(element) add an element to the set
collection.remove(element) Delete the specified element in the collection
collection.pop() Randomly remove an element from a collection
Set.clear() clear collection
set1.difference(set2) Get a new set, which contains the difference set of the two sets, and the original set remains unchanged
set1.difference_update(set2) Remove elements that exist in set 2 from set 1, set 1 changes, set 2 remains unchanged
Collection 1.union(collection 2) Get a new collection that contains all the elements of the two collections, and the original collection remains unchanged
len(collection) Count the number of elements in the collection (after deduplication)

Thank you for watching! I hope this article can help you!
The python column is constantly being updated, welcome to subscribe!
"Wish to encourage you and work together!"
insert image description here

Guess you like

Origin blog.csdn.net/m0_63463510/article/details/130536485