With the old Ziko Python collection (set)

Source: Internet
Author: User
Review the data types that you already know: Int/str/bool/list/dict/tuple

It's really quite a lot.

However, Python is a language of development, and it might be something else later. Crossing may have doubts, out of so many data types, I can not remember ah, especially inside there are many methods.

Don't worry about remembering, just remember what Einstein said.

Einstein's speech in the United States, someone asked: "You can remember how fast the sound?" How do you write down many things? Einstein easily replied: "What is the speed of the sound, I must look up the dictionary to answer." Because I never remember what has been printed in the dictionary, my memory is used to memorize things that are not in the book. ”

What a domineering answer, this answer is not only domineering, but also tells us a method: As long as it can be found in some way, there is no need to remember.

So, the various methods of the above data types do not need to be remembered, because they can be found by the following methods, but not limited to these methods (the logic of this sentence is still relatively strict, including but not limited to ...)

In interactive mode with Dir () or help ()
Google (not recommended Xdu, reasons for their own experience)

In order to be able to understand the types of data that have been studied in general, we might do the following:

1. Whether it is a sequence type: that is, whether the element of the data can be indexed. Include Str/list/tuple for sequence types
2. Whether the elements of the data can be modified in situ (especially to remind crossing, here is the original modification, some of the information that STR can not be modified, but also refers to the original modification.) to avoid misunderstandings, especially when the original is changed. To be able to modify the list/dict (special instructions, Dict key must be non-modifiable, dict value can be modified in situ)
What is the original change? Crossing can you explain it in interactive mode by example?

Here, crossing do not think this is a refresher lesson. The main content of this lecture is not to review, the main content is to introduce a new data type: Set (set) to crossing. Completely fainted, exactly how many data types does Python have? Another one more.

Basically, there are a lot of data types in Python, because everyone can define a data type by themselves. However, Python officially recognizes or says that the built-in data types are just a few. Basically today's set is finished, almost. In the course of future development, The data types included today and in the past are commonly used. Of course, you can define one yourself, but it's better to be native.

Create set

A tuple is a mix of list and str (hybrids have their own advantages, the last section has been shown), then set can be called List and dict of the hybrid.

The set has a feature similar to dict: it can be defined with the {} curly braces, where the element has no sequence, that is, data of a non-sequential type, and the elements in the set are not repeatable, which is similar to the Dict key.

Set also has inherited a point list of features: If you can modify the original (in fact, a category of set can be modified in situ, the other is not).

Here's an experiment to further understand how to create a set:

>>> S1 = set ("Qiwsir") #把str中的字符拆解开 to form set. Pay special attention to the observation that there are two i>>> S1 #但是在s1中 in Qiwsir         , only one I, that is, cannot repeat set ([ ' Q ', ' I ', ' s ', ' R ', ' W ']) >>> s2 = set ([123, "Google", "Face", "book", "Facebook", "book"])  #通过list创建set. No duplicates. , elements can be int/str>>> s2set ([' Facebook ', 123, ' Google ', ' book ', ' Face '])        #元素顺序排列不是按照指定顺序 >>> s3 = {" Facebook ", 123}    #通过 {} created directly >>> s3set ([123, ' Facebook '])

Then boldly do a few exploration, please crossing attention to observe the results:

>>> s3 = {"Facebook", [, ' a '],{"name": "Python", "Lang": "Chinese"},123}traceback (most recent call last): File "
 
  
   
  ", line 1, in 
  
   
    
   typeerror:unhashable type: ' dict ' >>> s3 = {"Facebook", [1,2],123} Traceback (most recent): File "
   
    
     
    ", line 1, in 
    
     
      
     typeerror:unhashable type: ' List '
    
     
   
    
  
   
 
  

As you can see from the above experiment, you cannot create a set that contains a LIST/DICT element through {}.

Continue to explore a situation:

>>> S1set ([' Q ', ' I ', ' s ', ' R ', ' W ']) >>> s1[1] = "I" Traceback (most recent call last): File "
 
  
    ", line 1, in 
  
   
    
   TypeError: ' Set ' object does not the 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, set and list made a comparison, although both can be changed in the same place, but by the index number (offset) of the way, directly modified, List allows, but set error.

So how does the set change?

Change set

or using the self-study method that has been introduced many times before, set the relevant built-in function to find out, 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 put the Double dash __ start first Delete (we will have a topic to tell about these):

' Add ', ' clear ', ' copy ', ' Difference ', ' difference_update ', ' discard ', ' intersection ', ' intersection_update ', ' Isdisjoint ', ' issubset ', ' issuperset ', ' Pop ', ' Remove ', ' symmetric_difference ', ' symmetric_difference_update ', ' Union ', ' Update '

Then use Help () to find out how each function is used, and here are a few examples:

add element

>>> Help (Set.add)-on Method_descriptor:add (...) Add an element to a set. This have no effect if the element is already present.

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

>>> a_set = {}       #我想当然地认为这样也可以建立一个set >>> a_set.add ("Qiwsir")   #报错. Look at the error message, Actually told me Dict did not add. I set up a set. Traceback (most recent called last): File "
 
  
   
  ", line 1, 
  
   
    
   in Attributeerror: ' Dict ' object has no attribute ' add ' >>> type (a_set)       #type之后发现, the computer thought I was building a dict   
   
     
    
  
   
 
  

Specifically, {} This thing is used in both dict and set. However, as the above method establishes dict, it is not set. This is the Python rule. To set up, you can only use the method described earlier.

>>> A_set = {' A ', ' I '}    #这回就是set了吧 >>> type (a_set) 
 
  
   
         #果然 >>> a_set.add (" Qiwsir ")   #增加一个元素 >>> a_set          #原处修改, that is, the original A_set reference object has changed set ([' I ', ' a ', ' Qiwsir ']) >>> B_set = set ( "Python") >>> type (b_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 ([+])   # This is no drop, as before, error. Traceback (most recent): File "
   
    
     
    ", line 1, in 
    
     
      
     typeerror:unhashable type: ' List ' >>> B_set.add (' [x-y] ')  #可以这样!>>> b_setset ([' [' [+] ', ' h ', ' o ', ' n ', ' P ', ' t ', ' Qiwsir ', ' x ') ')
    
     
   
    
  
   
 
  

In addition to the above method of adding elements, it is also possible to merge elements 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)    #把s2的元素并入到s1中 .>>> s1         #s1的引用对象修改set ([' A ', ' Qiwsir ', ' B ', ' GitHub ') >> > S2         #s2的未变set ([' GitHub ', ' Qiwsir ')

Delete

>>> Help (Set.pop) pop (...)  Remove and return an arbitrary set element.  Raises keyerror if the set is Empty.>>> b_setset ([' [[+] ', ' h ', ' o ', ' n ', ' P ', ' t ', ' qiwsir ', ' y ']) >>> B_set.pop ()   #从set中任意选一个删除 and returns the value ' [] ' >>> b_set.pop () ' H ' >>> b_set.pop () ' O ' >>> b_ Setset ([' N ', ' P ', ' t ', ' qiwsir ', ' y ']) >>> B_set.pop ("n") #如果要指定删除某个元素, error. Traceback (most recent): File "
 
  
   
  ", line 1, in 
  
   
    
   typeerror:pop () takes no arguments (1 g Iven)
  
   
 
  

Set.pop () is any element selected from the set, and the value is deleted and returned. However, you cannot specify that an element be deleted. The error message tells us that pop () cannot have parameters. In addition, if set is empty, an error is also given. This is a help message to tell us, crossing can try.

To delete the specified element, what should I do?

>>> Help (Set.remove) remove (...)  Remove an element from a set; It must be a member.    If the element is not a member, obj in raise a KeyError.set.remove (obj) must be an element in the set, otherwise an error is required. Try:>>> a_setset ([' I ', ' a ', ' Qiwsir ']) >>> a_set.remove ("i") >>> a_setset ([' A ', ' Qiwsir ']) >>> a_set.remove ("W") Traceback (most recent): File "
 
  
   
  ", line 1, in 
  
   
    
   keyerror: ' W '
  
   
 
  

Similar to remove (obj) is 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, does nothing.
Compare the information with help (set.remove) to see what's different. obj in discard (obj) if it is an element in set, delete it, and if it is not, do nothing. The news is going to be a comparison. It's the same here.

>>> A_set.discard (' a ') >>> a_set    Set ([' Qiwsir ') >>> a_set.discard (' B ') >>>

On the delete, there is also a lore, that is Set.clear (), its function is: remove all elements from the this set. (Crossing himself in interactive mode help (Set.clear))

>>> a_setset ([' Qiwsir ']) >>> a_set.clear () >>> a_setset ([]) >>> bool (a_set)   # Empty, bool. Return to False.false

Knowledge

Collection, also a mathematical concept (hereinafter defined from Wikipedia)

Collection (or short set) is the basic mathematical concept, which is the object of set theory. The simplest argument is that in the most primitive set theory-the definition of the simple set theory-the set is "a pile of things". The "thing" in the collection is called an element. If x is the element of a set A, it is recorded as X∈a.

Set is an important basic concept in modern mathematics. The basic theory of set theory was not founded until the end of 19th century, and it is now a ubiquitous part of mathematics education, and has been studied in elementary school. Here is a brief and basic introduction to what mathematicians call "intuitive" or "plain" set theory, and a more detailed analysis of the simple set theory. A rigorous axiom derivation of a set of visible axiomatic set theory.

What is a collection in a computer? also from Wikipedia, so to speak:

In computer science, a collection is a combination of a variable number of data items (or perhaps 0) that may share certain characteristics and need to be manipulated in some way. In general, the types of these data items are the same, or the base class is the same (if the language used supports inheritance). A list (or array) is generally not considered a collection because it is fixed in size, but it is often used in implementations as a collection of certain forms. The types of collections include lists, sets, multiset, trees, and graphs. An enumeration type can be a list or a set.

Whether you understand it or not, it seems very powerful.

Yes, so this is just a primer on the set. More operations on collections, such as operations/comparisons, are not yet covered.

  • 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.