Learn the Python set of sets

  • 2020-04-02 14:07:34
  • OfStack

Review already know the type of data: int/STR/bool/list/dict/tuple

That's a lot.

However,python is a developing language, and there may be others in the future.

Don't worry if you can't remember what Einstein said.


 Einstein gave a speech in the United States and someone asked, "do you remember what the speed of sound is? How do you remember a lot of things?" 
 Einstein replied easily, "what is the speed of sound? I have to look it up in a dictionary. For I never remember what is printed in the dictionary. My memory is for what is not printed in the book." 

How domineering answer, this answer is not only domineering, but also in a way to tell us: as long as we can find through a certain method, there is no need to remember.

Then, all methods of the above data types do not need to be memorized, because they can be found through the following methods but not limited to them.

Dir () or help() in interactive mode
Google (I don't recommend Xdu for my own reasons)

In order to have a general understanding of the data types we have studied, we might as well make the following classification:

1. Whether it is of sequence type: that is, whether the elements of the data can be indexed
2. If you can place changes: the elements of the data can be place changes (special remind reader, there are changes, some data inside said STR cannot be modified, is also refers to the place change problem. In order to avoid misunderstanding, with particular emphasis on the place). To be able to place is modified list/dict (special specifications, dict keys must be immutable, dict value can place changes)
What to change in place ? Can you explain it by examples in interactive mode?

The main content of this lecture is not to review, but to introduce the reader to a new data type: set. There's one more.

Said, from the basic point in python data types can be many, because everyone can define a data type. However, python official sanction or built-in data types, and then several. Basically set finished today, is about the same. In the later development process, including today and introduce the data type of the past, is commonly used. Of course, define your own a can also, but the use of the native is better.

Create a set

Tuple is the heterozygosity of list and STR (hybrid has its own advantages, as shown at the end of the previous section), and set can be regarded as the heterozygosity of list and dict.

Set has dict-like features: it can be defined with {} curly braces; The elements have no sequence, that is, the non-sequence type of data; Also, the elements in a set are not repeatable, which is similar to dict's keys.

Set also inherits some of the features of list: it can be modified in place (in fact, it can be modified in place for one set and not for the other).

The following is an experiment to further understand how to create a set:


>>> s1 = set("qiwsir") # the str The characters in , The formation of set. Pay special attention to :qiwsir There are two i
>>> s1         # But in the s1 In the , There is only one i, Which means you can't repeat it 
set(['q', 'i', 's', 'r', 'w'])

>>> s2 = set([123,"google","face","book","facebook","book"])  # through list create set. There can be no repetition , The element could be int/str
>>> s2
set(['facebook', 123, 'google', 'book', 'face'])        # Elements are not arranged in the specified order 

>>> s3 = {"facebook",123}    # through {} Directly to create 
>>> s3
set([123, 'facebook'])

A few more bold exploration, please pay attention to the observation results:


>>> s3 = {"facebook",[1,2,'a'],{"name":"python","lang":"english"},123}
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

>>> s3 = {"facebook",[1,2],123}
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

From the above experiment, you can see that a set containing a list/dict element cannot be created with {}.

Continue to explore a situation:


>>> s1
set(['q', 'i', 's', 'r', 'w'])
>>> s1[1] = "I"
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support item assignment

>>> s1   
set(['q', 'i', 's', 'r', 'w'])
>>> lst = list(s1)
>>> lst
['q', 'i', 's', 'r', 'w']
>>> lst[1] = "I"
>>> lst
['q', 'I', 's', 'r', 'w']

In the above exploration, a comparison is made between set and list. Although both can be modified in situ, they can be directly modified by means of index number (offset). List is allowed, but set reports an error.

So, how do you modify a set ?

Changes to the set

Still use the method of self-study that has been introduced many times before, find out about the built-in function of set, see what can be done to set.


>>> dir(set)
['__and__', '__class__', '__cmp__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']

In order to see clearly, I will delete the beginning of the double line.

'add' and 'clear' and 'copy' and 'difference', 'difference_update', 'this',' intersection computes', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update'

Then use help() to find out how to use each function. Here are some examples:

Add elements


>>> help(set.add)

Help on method_descriptor:

add(...)
Add an element to a set. 
This has no effect if the element is already present.

Here's an experiment in interactive mode, the best lab:


>>> a_set = {}       # I took it for granted that this would also build one set
>>> a_set.add("qiwsir")   # An error . Look at the error message , To tell me dict There is no add. What I've clearly established is that set ah .
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'add'
>>> type(a_set)       #type After the discovery , The computer thinks I'm building a dict   
<type 'dict'>

In particular,{} is used in both dict and set. However, the above method is dict, not set.


>>> a_set = {'a','i'}    # This time is set !! 
>>> type(a_set)
 <type 'set'>       # Sure enough 

>>> a_set.add("qiwsir")   # Add an element 
>>> a_set          # Place to modify , That is the original a_set The reference object has changed 
set(['i', 'a', 'qiwsir'])

>>> b_set = set("python")
>>> type(b_set)
<type 'set'>
>>> b_set
set(['h', 'o', 'n', 'p', 't', 'y'])
>>> b_set.add("qiwsir")
>>> b_set
set(['h', 'o', 'n', 'p', 't', 'qiwsir', 'y'])

>>> b_set.add([1,2,3])   # You can't do that , Same as before , An error .
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> b_set.add('[1,2,3]')  # It can be !
>>> b_set
set(['[1,2,3]', 'h', 'o', 'n', 'p', 't', 'qiwsir', 'y'])

In addition to the add element method above, you can also merge elements from another set, set.update(s2)


>>> help(set.update)
update(...)
  Update a set with the union of itself and others.

>>> s1
set(['a', 'b'])
>>> s2
set(['github', 'qiwsir'])
>>> s1.update(s2)    # the s2 The elements of s1 In the .
>>> s1         #s1 Reference object modification 
set(['a', 'qiwsir', 'b', 'github'])
>>> s2         #s2 The unchanged 
set(['github', 'qiwsir'])

delete


>>> help(set.pop)
pop(...)
  Remove and return an arbitrary set element.
  Raises KeyError if the set is empty.

>>> b_set
set(['[1,2,3]', 'h', 'o', 'n', 'p', 't', 'qiwsir', 'y'])
>>> b_set.pop()   # from set And delete any one of them , And returns the value 
'[1,2,3]'
>>> b_set.pop()
'h'
>>> b_set.pop()
'o'
>>> b_set
set(['n', 'p', 't', 'qiwsir', 'y'])

>>> b_set.pop("n") # If you want to specify the deletion of an element , An error in the .
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: pop() takes no arguments (1 given)

Set.pop () selects an element from a set, deletes it, and returns the value. However, it cannot be specified to delete an element.

What to do to delete the specified element ?


>>> help(set.remove)

remove(...)
  Remove an element from a set; it must be a member.  

  If the element is not a member, raise a KeyError.
set.remove(obj) In the obj, It must be set The elements in the , Otherwise, report an error . Give it a try :

>>> a_set
set(['i', 'a', 'qiwsir'])
>>> a_set.remove("i")
>>> a_set
set(['a', 'qiwsir'])
>>> a_set.remove("w")
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
KeyError: 'w'

Similar to remove(obj), there is another one:

> > > Help (the set. The discard)

The discard (...).
      Remove an element from a set if it is a member.

      If the element is not a member, do nothing.
Compare that with help(set. Remove) and see what's different. Obj in 'obj' is deleted if it's an element in 'set'. If it's not,do nothing.


>>> a_set.discard('a')
>>> a_set    
set(['qiwsir'])
>>> a_set.discard('b')
>>>

Remove all elements from this set. Remove all elements from this set.


>>> a_set
set(['qiwsir'])
>>> a_set.clear()
>>> a_set
set([])
>>> bool(a_set)   # empty ,bool The return False.
False

knowledge

Set is also a mathematical concept (the following definition is from wikipedia)

Set (or set for short) is a basic mathematical concept, and it is the research object of set theory. The simplest way to say it is that in the original set theory, naive set theory, a set is defined as "a bunch of things." The "things" in a set are called elements. If x is an element of set A, call it x ∈ A.

Set is an important basic concept in modern mathematics. The basic theory of set theory was not established until the end of the 19th century and is now a common part of mathematics education, learned in elementary school. Here is a brief but basic introduction to what mathematicians call "intuitive" or "naive" set theory; A more detailed analysis can be seen in naive set theory. The axiomatic set theory can be seen from the strict axiomatic derivation of sets.

In a computer, what is a set ? Also from wikipedia:


 In computer science, a set is a variable number of data items 0 These data items may share certain characteristics and need to be operated on together in a certain way. In general, these data items are of the same type or base class (if the language supports inheritance). A list (or array) is not usually considered a collection because of its fixed size, but in fact it is often used in implementations as some form of collection. 
 Types of collections include lists, sets, multiplexes, trees, and graphs. Enumeration types can be lists or sets. 

Whether you understand it or not, it seems pretty cool.

Yes, so this tutorial is just an introduction to sets. More operations on sets such as operations/comparisons are not covered yet.


Related articles: