With the old Ziko Python collection (set) _python

Source: Internet
Author: User
Tags stdin

Review the data types you already know: Int/str/bool/list/dict/tuple

It's really quite a lot.

But Python is a developing language, and maybe something else will come out later. Reader may have doubts, out of so many data types, I also remember Ah, especially there are many ways.

Don't be afraid to remember, you just have to remember what Einstein said.

Einstein spoke in the United States, and someone asked, "Do you remember how fast the sound is?" How do you write down a lot of things?
Einstein replied easily: "The speed of the voice is how much, I have to look up a dictionary to answer." Because I never remember what is printed on a dictionary, my memory is used to memorize things that are not in the books. ”

How domineering the answer, this answer is not only domineering, but also tells us a way: as long as the ability to find through some way, do not need memory.

So, the various methods of data types above do not need to be remembered, because they can be found in the following ways, but not limited to these methods (the logic of this sentence is more rigorous, including but not limited to ...)

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

To be able to have a general understanding of the types of data that have been studied, we may wish to classify the following:

1. Is the sequence type: that is, the elements of the data can be indexed. Where the sequence types include Str/list/tuple
2. Whether it can be modified in situ: that is, whether the elements of the data can be modified in situ (especially to remind reader, here is said to modify the problem, and some data said STR can not be modified, but also refers to the original change.) Dict key must be not modifiable, dict value can be modified in situ)
What is the original change? Reader can you explain it in interactive mode through an example?

Here, reader should not think that this is a review class. The main content of this lecture is not review, the main content is to introduce a new data type to reader: set. Completely fainted, how many data types does Python have? One more.

Basically, there can be a lot of data types in Python, because everyone can define a data type on their own. However, the Python official endorsement or the built-in data type, there are several. Basically today's set is finished, and it's almost done. In the future development process, Including the data types that are introduced today and in the past, are commonly used. Of course, it's OK to define one yourself, but better with the original.

Create set

Tuple is a combination of list and STR (hybrids have their own advantages, the last of which has been shown), then set can be called List and dict of the hybrid.

The set has a similar dict feature: it can be defined with {} curly braces, where the elements have no sequences, that is, data that is not a sequence type, and the elements in the set cannot be duplicated, which is similar to the Dict key.

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

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

>>> S1 = set ("Qiwsir") #把str中的字符拆解开 to form a set. Special attention observed: Qiwsir has two I
>>> s1         #但是在s1中, only one I, that is, cannot repeat
set ([' Q ', ' I ', ' s ', ' R ', ' W '])

>>> s2 = set ([123, "Google", "Face", "book", "Facebook", "book"])  # Create set from list. Cannot have duplicates, elements can be int/str
>>> S2
Set ([' Facebook ', 123, ' Google ', ' book ', ' Face '])        # Element order is not arranged in the specified order

>>> s3 = {"Facebook", 123}    #通过 {} directly create
>>> S3
Set ([123, ' Facebook ' ])

Again bold to do a few inquiries, please reader attention to observe the results:

>>> s3 = {"Facebook", [1,2, ' a '],{"name": "Python", "Lang": "中文版"},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, it can be seen that a set containing list/dict elements cannot be created through {}.

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, the set and list are compared, although both can be modified in situ, but, through the index number (offset) of the way, directly modified, list allowed, but set error.

So, how does set change?

Change set

or using the Self-Study method that has been introduced many times before, find out about the built-in functions of set, and see what you can do with 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 crossed the beginning of the first delete (we will have a topic to describe 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:

adding elements

>>> Help (Set.add)

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 = {}       #我想当然地认为这样也可以建立一个set
>>> a_set.add ("Qiwsir")   #报错. Look at the error message. Actually told me Dict didn't add. I have set it up clearly.
Traceback (most recent):
 File "<stdin>", line 1, in <module>
attributeerror: ' Dict ' object h As no attribute ' add '
>>> type (a_set)       #type之后发现, the computer thinks I'm building a dict   
<type ' dict ' >

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

>>> A_set = {' A ', ' I '}    #这回就是set了吧
>>> type (a_set)
 <type ' Set ' >       #果然

> >> A_set.add ("Qiwsir")   #增加一个元素
>>> a_set          #原处修改 that the original A_set 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< C17/>set ([' H ', ' o ', ' n ', ' P ', ' t ', ' qiwsir ', ' y '])

>>> b_set.add ([1,2,3])   #这样做是不行滴, as before, the error.
Traceback (most recent):
 File "<stdin>", line 1, in <module>
typeerror:unhashable type: ' List '

>>> b_set.add (' [1,2,3] ')  #可以这样!
>>> b_set
Set ([' [1,2,3] ', ' h ', ' o ', ' n ', ' P ', ' t ', ' qiwsir ', ' y '])

In addition to the above method of adding elements, it is 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.

>>> S1
Set ([' A ', ' B '])
>>> S2
Set ([' GitHub ', ' Qiwsir '])
>>> s1.update (s2 )    #把s2的元素并入到s1中.
>>> S1         #s1的引用对象修改
Set ([' A ', ' Qiwsir ', ' B ', ' GitHub '])
>>> S2         #s2的未变
Set ( [' GitHub ', ' Qiwsir '])

Delete

>>> Help (Set.pop)
POPs (...)
  Remove and return a 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 ()   # Select any deletion from set and return 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") #如果要指定删除某个元素, an error has been made. C16/>traceback (most recent):
 File "<stdin>", line 1, in <module>
Typeerror:pop () takes n o Arguments (1 given)

Set.pop () is an arbitrary selection of elements from the set. Delete and return this value. However, you cannot specify that an element be deleted. The error message tells us that pop () cannot have parameters. Also, if the set is empty, the error is not available. This is a help message, reader can try it.

What to do if you want to delete the specified element?

>>> Help (Set.remove)

Remove (...)
  Remove an element from a set; It must be a.  

  If the element is not a, raise a keyerror.
Obj in Set.remove (obj) must be an element in set, otherwise an error will be added. Try it:

>>> a_set
Set ([' I ', ' a ', ' Qiwsir '])
>>> A _set.remove ("i")
>>> a_set
Set ([' A ', ' Qiwsir '])
>>> a_set.remove ("W")
Traceback (most recent):
 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.

If the element is not a and 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 must be contrasted to see what it means.

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

There is also a lore on deletion, that is set.clear (), its function is: remove all elements to this set. (Reader oneself in interactive mode help (Set.clear))

>>> a_set
Set ([' Qiwsir '])
>>> a_set.clear ()
>>> a_set
set ([])
>>> bool (a_set)   #空了, BOOL returns FALSE.
False

Knowledge

Collection, also a mathematical concept (the following definition comes from Wikipedia)

Set (or short term sets) is the basic mathematical concept, it is the research object of set theory. The simplest of all is the definition in the most primitive set theory-the plain set theory-that the collection is "a pile of things". The "thing" in the collection is called an element. If x is the element of set A, it is x∈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, and it is now a ubiquitous part of mathematics education and began to study in elementary school. This is a brief and basic introduction to what mathematicians call "intuitive" or "plain" set theory, and the more detailed analysis shows the naïve set theory. A rigorous axiom derivation of the set shows 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 (and possibly 0) that may share some features and need to be manipulated in some way. Generally, the types of these data items are the same, or the base class is the same (if you are using a language that supports inheritance). A list (or array) is usually not considered a collection because its size is fixed, but in fact it is often used as a collection of some forms in the implementation.
the types of collections include lists, sets, multiple sets, trees, and graphs. An enumeration type can be a list or set.

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

Yes, so this is just an introduction to the collection. More operations on collections, such as operations/comparisons, have not yet been addressed.

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.