Learning programming is easy and rough. Most of the time, the more you learn, the faster you forget. But programming always has an Epiphany, and the moment of Epiphany is currently based on you and eraser stick to punch for 100 days, in the comments section of eraser stick to learn from eraser, after 100 days, eraser will send out a mysterious prize.

This series of articles will be completed before the Spring Festival of 2021, welcome to follow, like, comment -- dream eraser

An unordered, element-unique data type in Python. It is a collection.

8.1 What is a set

A collection is a data type in which each element is in a variable but unique order. How round a word, aftertaste, must have a good aftertaste.

Elements in a collection must be immutable types, such as integers, floating point numbers, strings, and tuples. Mutable lists, dictionaries, and collections cannot be.

Collections themselves are mutable, adding and removing elements just like lists.

8.1.1 Declaration of collections

Until now, brackets declared tuples, brackets declared lists, and braces declared dictionaries. What about collections? Python also uses braces to declare collections. Of course, you can also build sets by using the set function.

The syntactic format for a collection definition is as follows:

My_set = {element1Elements,2. }Copy the code

A simple code example is as follows:

my_set = {1.2.3.3.10.4.5.6}

print(my_set)
Copy the code

After the data is output, there is only one duplicate integer 3 left. Again, because the elements of the set are unique, the parts with many repetitions will be dropped.

An error is reported if a mutable type is used as an element in a collection.

my_set = {1.2.3[3.10.4.5.6]}
TypeError: unhashable type: 'list' TypeError: unhashable type: 'list'
print(my_set)
Copy the code

It is important to note that empty collections cannot be declared with {}, only curly braces denote an empty dictionary. To declare an empty set, we use the set function.

8.1.2 The set function defines a set

Sets can be defined using the set function, and empty sets can be defined. Set can be a string, a list, or a tuple.

Define an empty collection by set

my_dict = {}
my_set = set(a)# empty dictionary
print(type(my_dict))
# empty collection
print(type(my_set))
Copy the code

Set converts strings into collections

The set function is like a cast that can convert other types to collections.

my_set = set("my name is xiangpica")
print(my_set)
Copy the code

This content filters repeated letters, and the output order is variable because the collection is unordered.

Sets can de-duplicate tuples

By not allowing repetition of collection elements, you can achieve certain effects, such as de-weighting.

my_tuple = ("apple"."orange"."orange"."pear"."banana"."food")
my_set = set(my_tuple)
print(my_set)
Copy the code

8.2 Operation of collections

Before we can do anything with sets, we need to learn some symbols.

symbol meaning
& intersection
| And set
Difference set
^ Symmetric difference set

And then we’re going to do something very similar to what we did in the high school line generation, which is to find the intersection difference set of sets.

8.2.1 Intersection

Intersection is finding the elements that are common to two sets.

my_set1 = {"apple"."orange"."pear"."banana"."food"}
my_set2 = {"apple"."orange"."pear"}

both = my_set1 & my_set2
print(both)
Copy the code

In addition to the ampersand, this is done through the collection intersection method.

my_set1 = {"apple"."orange"."pear"."banana"."food"}
my_set2 = {"apple"."orange"."pear"}

both = my_set1.intersection(my_set2)
print(both)
Copy the code

8.2.2 Union (Union)

Union is taking all the elements of all the sets, keeping one if there’s a duplicate. Use symbol | or union method to complete.

my_set1 = {"apple"."orange"."pear"."banana"."food"}
my_set2 = {"apple"."orange"."pear"}

both = my_set1 | my_set2
print(both)
Copy the code

Use union to do this.

my_set1 = {"apple"."orange"."pear"."banana"."food"}
my_set2 = {"apple"."orange"."pear"}

both = my_set1.union(my_set2)
print(both)
Copy the code

8.2.3 Difference

For the difference set and the union set, there is A sequencing problem, for example, A member of A but not A member of B is A minus B, and A member of B but not A is B minus A.

The sign for the difference set is -, and you can use the difference method.

my_set1 = {"apple"."orange"."pear"."banana"."food"}
my_set2 = {"apple"."orange"."pear"."grape"}
Solve for the elements that belong to A, but not to B
dif1 = my_set1 - my_set2
print(dif1)
Solve for the elements that belong to B, but not to A
dif2 = my_set2 - my_set1
print(dif2)
Copy the code

How to use the difference method to find the difference set is up to you.

8.2.4 Symmetric Difference Set

Two sets, A and B, if you want to get elements that belong to A or B, but not elements that belong to A and belong to B, then this is the application scenario of symmetric difference set.

The symbol for the symmetric difference set is ^, and the method name is symmetric_difference.

my_set1 = {"apple"."orange"."pear"."banana"."food"}
my_set2 = {"apple"."orange"."pear"."grape"}

dif = my_set1 ^ my_set2
print(dif)
Copy the code

The above code outputs elements that are neither A nor B, the set of symmetric differences.

8.3 Method of collection

8.3.1 Adding and deleting collections

The add method adds elements to a collection in the following syntax:

My_set.add (new element)Copy the code

The first element that needs to be noted will not be added if it already exists in the collection. The second element needs to be noted is that the collection is unordered and the position of the newly added element will not be determined.

my_set = {"apple"."orange"."pear"."grape"}
my_set.add("new")
my_set.add("new")
print(my_set)
Copy the code

The remove method can remove an element from a collection if the element is in the collection. An error is reported if you remove an element that does not exist.

my_set = {"apple"."orange"."pear"."grape"}

my_set.remove("apple")

print(my_set)
The second delete failed because Apple is no longer in the collection
my_set.remove("apple")
print(my_set)
Copy the code

The discard method deletes a collection element without an error if the element does not exist.

my_set = {"apple"."orange"."pear"."grape"}

my_set.discard("apple")
print(my_set)

my_set.discard("apple")
print(my_set)
Copy the code

The pop method deletes a random element, and the deleted element is returned. You can use a variable to receive the deleted element. If the collection is empty, pop will cause an error.

my_set1 = {"apple"."orange"."pear"."grape"}

The # pop method randomly removes an element and returns the deleted element
var = my_set1.pop()
print(var)

# empty collection using pop method error
my_set2 = set()
var = my_set2.pop()
print(var)
Copy the code

The clear method removes all elements in the collection

my_set1 = {"apple"."orange"."pear"."grape"}

my_set1.clear()
print(my_set1)
Copy the code

8.3.1 Other methods for collections

The isdisJoint method is used to determine whether two sets have the same element, returning True if not, and False otherwise.

my_set1 = {"apple"."orange"."pear"."grape"}
my_set2 = {"banana"."watermelon"}

The two sets have no identical elements
ret_bool = my_set1.isdisjoint(my_set2)
print(ret_bool) # returns True

my_set1 = {"apple"."orange"."pear"."grape"}
my_set2 = {"banana"."watermelon"."apple"}

Both sets have the same element
ret_bool = my_set1.isdisjoint(my_set2)
print(ret_bool)
Copy the code

Issubset This method is used to determine whether a subset is a subset of another subset, returning True if certain, and False otherwise.

my_set1 = {"apple"."orange"."pear"."grape"}
my_set2 = {"banana"."watermelon"}

# The second set is not a subset of the first set
ret_bool = my_set2.issubset(my_set1)
print(ret_bool) # returns False

# The second set is a subset of the first set
my_set1 = {"apple"."orange"."pear"."grape"}
my_set2 = {"orange"."apple"}

ret_bool = my_set2.issubset(my_set1)
print(ret_bool) # returns True
Copy the code

Pay attention to judge A is A subset of B, the format is A subset(B), the order is not wrong.

The issuperset method is used to determine whether a set is the parent of another set, which is the opposite of issubset, and the specific implementation is completed by everyone.

The update method is used to add elements from one collection to another in the following syntax:

Collection to be added A.update(Collection to be added B)Copy the code

The method is added to whoever comes first.

my_set1 = {"apple"."orange"."pear"."grape"}
my_set2 = {"banana"."watermelon"}

my_set1.update(my_set2)
print(my_set1)
Copy the code

Other methods, this round of snowball phase just do understanding.

  • Intersection_update This method is used to find the intersection of multiple sets
  • Difference_update removes elements within a collection that duplicate another collection
  • Symmetric_difference_update is similar to the use of symmetric difference sets

8.4 Built-in functions available for collections

8.4.1 Max, min, sum

The above built-in function scope collection is consistent with the list usage rules, you can test yourself.

8.4.2 len

Gets the number of collection elements.

8.4.3 sorted

Use this function to sort collections.

8.5 Freezing set FrozenSet

Elements in collections can be added and removed, corresponding to lists. There is also a set of elements that cannot be added or removed, called a frozen set, and tuples can be learned accordingly.

I’m not going to expand on frozen sets, but if you’re interested, you can retrieve some, but I think this is already a very long lecture.

8.6 Summary of this blog

Collection, an unordered container data type whose elements must be unique, is often used in eraser programming. Collections are efficient, easy to write, and worth learning.

Starting with the next blog post, we’ll dive into the world of Python functions

The last bowl of chicken soup

When you learn how to break things, you will find that the world suddenly opens up

🍂 🍂 🍂 🍂 🍂 🍂 🍂


Today is day 7/100 of continuous writing. If you have ideas or techniques you’d like to share, feel free to leave them in the comments section.


Blogger ID: Dream eraser, hope you like, comment, favorites.