A collection of Python (set) and a collection of python

Source: Internet
Author: User

A collection of Python (set) and a collection of python

Let's review the data types that we know: int/str/bool/list/dict/tuple.

A lot more.

However, python is a developing language. Maybe something else will happen in the future. the viewer may have doubts. I cannot remember the data types, especially the many methods.

Don't worry, you just need to remember what Einstein said.

When Einstein gave a speech in the United States, someone asked, "How fast do you remember the voice? How do you write down many things ?" Einstein replied easily: "How fast is the sound? I have to look up the dictionary to answer this question. Because I never remember what is printed on the dictionary, my memory is used to remember what is not in the book ."

What a domineering answer, this answer is not only domineering, but also tells us a way: as long as you can find it in some way, you do not need to remember it.

Therefore, there is no need to remember all the methods of the above data types, because they can all be found through the following methods, but not limited to these methods (the logic of this sentence is still relatively strict, including but not limited ...)

Use dir () or help () in interactive mode ()
Google (Xdu is not recommended for the reason)

To understand the data types that have been learned in general, we may wish to classify them as follows:

1. Whether it is a sequence type: whether the data element can be indexed. The sequence types include str/list/tuple.
2. whether it can be modified in the original place: whether the element of the data can be modified in the original place. (This is a special reminder to the reader. Here we are talking about the problem of the original modification. In some documents, str cannot be modified, it also refers to the original modification problem. in order to avoid misunderstanding, special emphasis is placed on the original position ). list/dict can be modified in the original place (in particular, the dict key must be unchangeable, And the dict value can be modified in the original place)
What is the original modification? Can I explain it through an instance in interactive mode?

Here, you should never think that this lecture is a review. the main content of this lecture is not a review. The main content is to introduce a new data type to the viewer: set ). how many data types does python have? There is another one.

Basically speaking, there are many data types in python, because everyone can define a data type. however, python officially recognizes or built-in data types. basically, today's set is finished. in the future development process, including the data types introduced today and in the past, are commonly used. of course, you can define one by yourself, but it is better to use native.

Create a set

Tuple is the combination of list and str (both of which have their own advantages and are shown after the end of the previous section). set can be called the combination of list and dict.

Set has the characteristics similar to dict: It can be defined by braces {}. The elements in the set have no sequence, that is, non-sequence data. Moreover, the elements in the set cannot be repeated, this is similar to the dict key.

Set also inherits the characteristics of a list: for example, it can be modified in the original place (in fact, a set of other types can be modified in the original place, and another type cannot be modified ).

The following describes how to create a set through an experiment:

>>> S1 = set ("qiwsir") # split the characters in str to form a set. note: qiwsir has two I >>> s1 # But in s1, there is only one I, that is, the set (['Q', 'I ', 'S ', 'R', 'w']) >>> s2 = set ([123, "google", "face", "book", "facebook ", "book"]) # create a set through list. there cannot be duplicates. The element can be int/str >>> s2set (['Facebook ', 123, 'Google', 'book', 'face']) # The element order is not in the specified order> s3 = {"facebook", 123} # directly create through {}> s3set ([123, 'Facebook '])

Make a few bold explorations. Please check the observations:

>>> 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 experiment above, we can see that {} cannot create a set containing the list/dict element.

Continue to explore a situation:

>>> s1set(['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, the set and list are compared. Although both can be modified in the original place, the index number (offset) is used to directly modify the list, but set reports an error.

So how can we modify the set?

Change set

You can also use the self-taught methods described previously to find out the built-in functions of the set to see what operations can be performed on the 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']

To make it clear, I will first Delete the dashes _ (we will discuss these topics later ):

'Add', 'clear', 'copy', 'difference ', 'difference _ Update', 'discard', 'intersection ', 'intersection _ Update', 'isdisjoint ', 'issubset', 'issuperset', 'pop', 'delete', 'random Ric _ difference ', 'random Ric _ difference_update', 'Union ', 'update'

Then you can use help () to find the specific usage of each function. The following are several examples:

Add Element

>>> help(set.add)Help on method_descriptor:add(...)Add an element to a set. This has no effect if the element is already present.

The following is an experiment in the best lab of interactive mode:

>>> A_set ={}# you can also create a set> a_set.add ("qiwsir") # report an error. check the error message and tell me that dict does not add. I have established a set. traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'dict 'object has no attribute 'add' >>> type (a_set) # after the type is found, the computer considers that I am creating a dict <type 'dict '>

Note that {} is used in both dict and set. however, the above method creates dict, not set. this is stipulated by python. to create a set, you can only use the method described above.

>>> A_set = {'A', 'I'} # set now >>> type (a_set) <type 'set'> # Sure enough> a_set.add ("qiwsir") # Add an element> a_set # modify the original position, that is, the original a_set reference object has changed set (['I', 'A', 'qiwsir ']) >>> B _set = set ("python") >>> type (B _set) <type 'set' >>> B _setset (['h', 'O', 'n', 'P','t ', 'y']) >>>> B _set.add ("qiwsir") >>> B _setset (['h', 'O', 'n', 'P','t ', 'qiwsir ', 'y']) >>> B _set.add ([1, 2, 3]) # This operation does not work. As before, an error is returned. traceback (most recent call last ): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'LIST' >>> B _set.add ('[1, 2, 3]') # Yes! >>> B _setset (['[1, 2, 3]', 'h', 'O', 'n', 'P', 't', 'qiwsir ', 'y'])

In addition to the added element method, the element can also be merged from another set by set. update (s2)

>>> Help (set. update) update (...) update a set with the union of itself and others. >>> s1set (['A', 'B'])> s2set (['github ', 'qiwsir'])> s1.update (s2) # merge s2 elements into s1. >>> s1 # modify the reference object set of s1 (['A', 'qiwsir ',' B ', 'github'])> s2 # set of s2 (['github ', 'qiwsir'])

Delete

>>> Help (set. pop) pop (...) remove and return an arbitrary set element. raises KeyError if the set is empty. >>> B _setset (['[1, 2, 3]', 'h', 'O', 'n', 'P', 't', 'qiwsir ', 'y']) >>> B _set.pop () # select any one from the set and return the value '[1, 2, 3]' >>> B _set.pop () 'H'> B _set.pop () 'O'> B _setset (['n', 'P', 't', 'qiwsir ', 'y']) >>> B _set.pop ("n") # If you want to delete an element, an error is returned. traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: pop () takes no arguments (1 given)

Set. pop () is to select any element from the set, delete it, and return this value. however, you cannot specify to delete an element. the error message tells us that pop () cannot have parameters. in addition, if set is empty, an error is returned. this article tells us the help information. You can try it.

What should I do if I want 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. the obj in remove (obj) must be an element in set; otherwise, an error is returned. a try: >>> a_setset (['I', 'A', 'qiwsir ']) >>> a_set.remove ("I") >>> a_setset (['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 also a discard (obj ):

>>> Help (set. discard)

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

If the element is not a member, do nothing.
And help (set. remove. if the obj in discard (obj) is an element in the set, it will be deleted. If not, nothing will be done. do nothing. news is more interesting than watching it. the same is true here.

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

There is also a kill on the deletion, that is, set. clear (). Its function is to Remove all elements from this set. (You can view help (set. clear) in interactive mode ))

>>> A_setset (['qiwsir ']) >>>a_set.clear () >>> a_setset ([]) >>> bool (a_set) # null, boolean returns False. false

Knowledge

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

Set is a basic mathematical concept. It is the object of the Study of set theory. The simplest statement is the definition in the original set theory-Simple set theory-where a set is "a bunch of things ". The "things" in the set are called elements. If 'X' is an element of 'A', it is recorded as 'X' and 'A.

Collection is an important basic concept in modern mathematics. The basic theory of set theory was not created until the end of the 19th century. It is now a common part of mathematics education and began to learn in elementary school. Here we will give a brief and basic introduction to the set theory called "Intuitive" or "simple" by mathematicians. For more detailed analysis, we can see the simple set theory. The Theory of Public Physical and Chemical sets can be seen from the strict derivation of the Theorem of the set.

What is a set in a computer? This is also from Wikipedia:

In computer science, a set is a combination of variable numbers of data items (or 0). These data items may share certain features and must be operated together in a certain way. Generally, these data items have the same type or the same base class (if the language used supports inheritance ). A list (OR array) is generally not considered a set because its size is fixed, but in fact it is often used as a set of some forms in implementation. The types of a set include list, set, multi-duplicated set, tree, and graph. The enumerated type can be list or set.

Whether you understand it or not, it looks amazing.

Yes, so this article only introduces the set. More operations on the set, such as calculation and comparison, are not involved yet.




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.