ArticleDirectory
- 1. List
- 2. tuples
- 3. Dictionary
- 4. Sequence
- 5. Set
- 6. Reference
- 7. More string content
- Summary:
8. Data Structure
A Data Structure is a data structure that can combine some data. In other words, it is used to store a group of related data. Python has four built-in data structures: List, tuples, dictionaries, and collections.
1. List
A list is a data structure used to save an ordered element set. You can store an element sequence in the list. Consider a shopping list that contains a list of items you want to purchase, but you may want to separate them with semicolons and convert them to commas (,) in Python.
The list element is included in square brackets, so that python will understand that you are specifying a list. After creating a list, you can add, delete, and search its elements. Because you can perform the add and delete operations, we call the list a variable type, that is, this type can be modified.
Quick introduction to objects and Classes
List is an example of using objects and classes. When we assign a value to variable I, for example, assign a value of 5, which is equivalent to creating an int class (type) object (Instance). You can refer to help (INT) to better understand it.
A class can also have methods, that is, functions, and they can only apply to this class. These functions can be used only when you have a class object. For example, Python provides an append method for the list to allow you to add elements to the end of the list table. For example, mylist. append ('an item') adds the string to the end of the list mylist. Note: Use the DoT number to access the object.
A class can also have fields, while a field is only a special application and a class variable. You can use these variables when you have objects of the corresponding class. The field is also accessed by the node number, for example, mylist. Field.
For example:
# Filename: using_list.py # This is my shopping listshoplist = ['apple', 'mango ', 'carrot', 'Banana'] print ('I have', Len (shoplist ), 'items to purchase. ') print ('these items are:', end = '') for item in shoplist: Print (item, end = '') print ('\ ni also have to buy rice. ') shoplist. append ('Rice ') print ('My shopping list is now', shoplist) print (' I will sort my list now ') shoplist. sort () print ('sorted shopping list is ', shoplist) print ('the first item I will buy is', shoplist [0]) olditem = shoplist [0] del shoplist [0] print ('I bought the', olditem) print ('My shopping list is right', shoplist)
Output:
C: \ Users \ Administrator> Python D: \ Python \ using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'Banana ', 'Rice']
I will sort my list now
Sorted shopping list is ['apple', 'Banana ', 'carrot', 'mango', 'Rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['bana', 'carrot', 'mango ', 'Rice']
Working principle:
The shoplist variable is the shopping list of a shopper. We only store the name string of the purchased item in shoplist, but you can also add any other types of objects to the List, including numbers or even other lists. We use... The in iteration list element. Now we can see that the list is actually a sequence.
Note that the print end keyword is a real parameter, which specifies that we want to end the output with a space instead of the normal line feed.
Next, we will use the append method of the list object to add a new element to the list. To ensure that the elements are actually added, we simply pass the list to the print function. The print function neatly prints the list content. Then we sort the list using the sort method of the list. Note that sort affects the list rather than returning a modified list. This is different from the way strings work, which is why class labels are variable types while strings are immutable types. After purchasing something in the market, we want to delete it from the list. The del statement is used here. Here, we specify the element in the list to be deleted, and De deletes the element from the list. We specify the first element of the list to be deleted, so we use del shoplist [0] (recall that the python index starts from 0 ).
If you want to know all the methods of the list object, see help (list ).
2. tuples
Tuples are used to save various objects. It is similar to the list, but it lacks many functions provided by the list. A major feature of the list is like a string, which is an unchangeable type, that is, you cannot modify tuples.
Tuples are defined by a set of elements separated by commas and closed with an optional parentheses.
Tuples are usually used in this case. A statement or a user-defined function can safely assume that a group of values (that is, the values of the tuples) It uses will not change.
For example:
# Filename: using_tuple.py zoo = ('python', 'elephant', 'penguin') # Remember the parentheses are optionalprint ('number of animals in the zoo is ', len (zoo) new_zoo = 'monkey', 'camel', zooprint ('number of cages in the new zoo is ', Len (new_zoo )) print ('All animals in new zoo are ', new_zoo) print ('animals brought from old zoo are', new_zoo [2]) print ('Last animal brought from old zoo is ', new_zoo [2] [2]) print ('number of animals in the new zoo is', Len (new_zoo) -1 + Len (new_zoo [2])
Output:
C: \ Users \ Administrator> Python D: \ Python \ using_tuple.py
Number of animals in the zoo is 3
Number of cages in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin ')
)
Animals brought from old zoo are ('python', 'elephant', 'penguin ')
Last animal brought from old zoo is penguin
Number of animals in the new zoo is 5
Working principle:
The variable zoo references a tuples. We can see that the Len function can get the length of the tuples. This also indicates that the tuples are also a sequence type. Next we will move these animals to a new Zoo. Therefore, new_zoo contains both existing animals and new animals transferred from the old zoo.
Note that a tuples contained in other meta groups do not lose their identities.
Like the list, we can use a pair of square brackets to specify the position of the element to access this element. This is called the index operator. We use new_zoo [2] to access the third element of new_zoo, and new_zoo [2] [2] to access the third element of new_zoo. 1. if you understand this language style, you will think this operation is too simple.
Parentheses
Although parentheses are optional, we strongly recommend that you stick to parentheses so that you can see at a glance that they are tuples, especially to avoid ambiguity.
For example, print (1, 2, 3) and print (1, 2, 3 )) is different-the former prints three numbers, and the latter prints a triple (including three numbers ).
Tuples with zero or one element
An empty tuples are created using empty parentheses, for example, myempty = ().
However, specifying a single-element tuples is not that intuitive. You must follow a comma after the only element, so that python can be distinguished.
What you want is a tuple rather than an expression of an object surrounded by parentheses. For example, if you want a single-element tuples with a value of 2, you must write it as Singleton = (2 ,)
Note: The list in the list will not lose its identity, that is, the list will not be dispersed as in Perl. The same is true for tuples, lists, lists, and so on. As long as it is Python, they only use another object for storage.
3. Dictionary
The dictionary is like an address book. You only need to know the contact name to find its address or details. That is, we associate the key (name) with the value (related information.
Note:
The key must be unique, as if two people have the same name, you cannot find the correct information.
The dictionary key must be an immutable object (such as a string), but the dictionary value can be a mutable or immutable object. Basically, this means that only simple objects can be used as keys.
The key-value pairs in the dictionary are specified using the syntax d = {key1: value1, key2: value2.
Note that their key/value pairs are separated by colons, and each pair is separated by commas, all of which are included in curly brackets.
Remember that the key/value pairs in the dictionary are unordered. If you want to arrange them in a specific order, you can only sort them before use.
The dictionary you actually use is a dict Class Object/instance.
For example:
# Filename: using_dict.py # 'AB' is short for 'A' ddress 'B' ook AB = {'swaroop ': 'swaroop @ swaroopch.com', 'Larry ': 'Larry @ wall.org ', 'matsumo': 'matz @ ruby-lang.org', 'spammer ': 'spammer @ hotmail.com'} print ("swaroop's address is ", AB ['swaroop ']) # deleting a key-value pairdel AB ['pemer'] print (' \ nthere are {0} contacts in the address-book \ n '. format (LEN (AB) for name, address in AB. items (): Print ('Contact {0} At {1 }'. format (name, address) # adding a key-Value Pair Rab ['guid'] = 'guido @ python.org 'If 'guid' in AB: print ("\ nguido's address is", AB ['guid'])
Output:
C: \ Users \ Administrator> Python D: \ Python \ using_dict.py
Swaroop's address is swaroop@swaroopch.com
There are 3 contacts in the address-book
Contact swaroop at swaroop@swaroopch.com
Contact Matsumoto at matz@ruby-lang.org
Contact Larry at larry@wall.org Guido's address is guido@python.org
Working principle:
We created the dictionary AB using the already described Mark. Then, we use the index operators that have been discussed in the list and metadata sections to specify keys and use key/value pairs. We can see that the dictionary syntax is also very simple.
We can use our old friends --Del
Statement to delete key/value pairs. We only need to specify the dictionary and the keys to be deleted using the index operator, and then pass themDel
Statement. When performing this operation, we do not need to know the value corresponding to that key.
Next, we use the dictionaryItems
To use each key/value pair in the dictionary. This returns a list of tuples, each of which contains a pair of project-keys and corresponding values. We crawl this pair and then assign itFor... in
Variable in LoopName
AndAddress
Then print these values in the for-block.
We can use the index operator to address a key and assign values to it. This adds a new key/value pair, just as we did for Guido in the above example.
We can useIn
Operator to check whether a key/value pair exists, or useDict
ClassHas_key
Method. You can useHelp (dict)
To viewDict
Complete method list of the class.
Keyword parameters and dictionaries
If you look at the keyword parameters you use in the function from another perspective, you have used the dictionary! Just think about the key/value pair you used in the parameter list defined by the function. When you use a variable in a function, it only uses a dictionary key (this is called a symbol table in terms of compiler design ).
4. Sequence
Lists, tuples, and strings are all sequences, but what are sequences? Why are they so special? The two main features of a sequence are index operators and slice operators. The index operator allows us to capture a specific item from the sequence. The three sequence types mentioned above-lists, tuples, and strings also support the slice operation, allowing us to get a slice of the sequence, that is, the part of the sequence.
For example:
# Filename: seq. PY shoplist = ['apple', 'mango', 'carrot', 'bana'] Name = 'swaroop '# indexing or 'subauthorization' operationprint ('item 0 is ', shoplist [0]) print ('item 1 is ', shoplist [1]) print ('item 2 is', shoplist [2]) print ('item 3 is ', shoplist [3]) print ('item-1 is ', shoplist [-1]) print ('item-2 is', shoplist [-2]) print ('character 0 is ', name [0]) # Slicing on a listprint ('item 1 to 3 is', shoplist []) print ('item 2 to end is ', shoplist [2:]) print ('item 1 to-1 is', shoplist [1:-1]) print ('item start to end is ', shoplist [:]) # Slicing on a stringprint ('characters 1 to 3 is', name []) print ('characters 2 to end is ', name [2:]) print ('characters 1 to-1 is', name [1:-1]) print ('characters start to end is ', name [:])
Output:
C: \ Users \ Administrator> Python D: \ Python \ seq. py
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item-1 is banana
Item-2 is carrot
Character 0 is S
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'bana']
Item 1 to-1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'bana']
Characters 1 to 3 is wa
Characters 2 to end is aroop
Characters 1 to-1 is waroo
Characters start to end is swaroop
Working principle:
First, we will learn how to use indexes to obtain a single item in the sequence. This is also called a subscript operation. Whenever you use a number in square brackets to specify a sequence, Python captures the items at the corresponding position in the sequence. Remember, Python starts counting from 0. Therefore, shoplist [0] crawls the first item and shoplist [3] captures the fourth element in the shoplist sequence.
The index can also be a negative number. In that case, the position is calculated from the end of the sequence. Therefore, shoplist [-1] indicates the last element of the sequence, while shoplist [-2] captures the second to last item of the sequence.
The Slice operator is a sequence name followed by a square bracket, which contains an optional number and is separated by a colon. Note that this is very similar to the index operator you are using. Remember that numbers are optional, while colons are required.
The first number (before the colon) in the slice operator indicates the start position of the slice, and the second number (after the colon) indicates the end of the slice. If the first number is not specified, Python starts from the beginning of the sequence. If the second number is not specified, Python stops at the end of the sequence. Note that the returned sequence starts from the starting position and ends just before the ending position. That is, the start position is included in the sequence slice, and the end position is excluded from the slice.
In this way, shoplist [] returns a sequence slice starting from position 1, including position 2, but stops at position 3. Therefore, it returns a slice containing two items. Similarly, shoplist [:] returns a copy of the entire sequence.
You can use a negative number for slicing. A negative number is used to start from the end of the sequence. For example, shoplist [:-1] returns a sequence slice that contains all projects except the last project.
In addition, you can also provide the third real parameter for the slice, which represents the step size (1 by default ).
>>> Shoplist = ['apple', 'mango', 'carrot', 'bana']
>>> Shoplist [: 1]
['Apple ', 'mango', 'carrot', 'bana']
>>> Shoplist [: 2]
['Apple', 'carrot']
>>> Shoplist [: 3]
['Apple', 'Banana ']
>>> Shoplist [:-1]
['Bana', 'carrot', 'mango', 'apple']
Note that when the step is 2, the index is 0, 2... . If the step is 3, the result is 0, 3 ..., And so on.
Use the python interactive interpreter (so that you can see the result immediately) to try the slice usage.
The best thing about sequence types is that you can access tuples, lists, and strings in the same way.
5. Set
A set is an unordered set of simple objects. It is applicable when you are more concerned about whether the elements in the set exist, not their order or the number of times they appear.
Using a set, you can test the subordination, whether a set is a subset of another set, or look for the intersection of two sets.
>>> Bri = set (['Brazil ', 'Russia', 'India '])
>>> 'India 'in BRI
True
>>> 'Usa' in BRI
False
>>> BRIC = Bri. Copy ()
>>> Bric. Add ('China ')
>>> Bric. issuperset (BRI)
True
>>> Bri. Remove ('Russia ')
>>> Bri & BRIC # Or Bri. Intersection (BRIC)
{'Brazil ', 'India '}
Working principle:
CodeIt is almost self-explanatory, because it involves basic set theory knowledge that we have learned in school.
6. Reference
When you create an object and assign it to a variable, the variable only references the object, and the variable does not represent the object itself. In other words, the variable name points to a portion of your computer's memory, which is used to store actual objects. This is called the binding of the name to the object.
Generally, you do not need to care about this, but you should know some minor influences caused by references.
For example:
# Filename: reference. PY print ('simple assignment ') shoplist = ['apple', 'mango', 'carrot ', 'bana'] mylist = shoplist # mylist is just another name pointing to the same object! Del shoplist [0] # I purchased the first item, so I remove it from the list print ('shoplist is ', shoplist) print ('mylist is', mylist) # notice that both shoplist and mylist both print the same list without # The 'apple' confirming that they point to the same object print ('Copy by making a full slice ') mylist = shoplist [:] # Make a copy by doing a full slicedel mylist [0] # Remove first item print ('shoplist is ', shoplist) print ('mylist is ', mylist) # notice that now the two lists are different
Output:
C: \ Users \ Administrator> Python D: \ Python \ reference. py
Simple assignment
Shoplist is ['mango', 'carrot', 'bana']
Mylist is ['mango', 'carrot', 'bana']
Copy by making a full slice
Shoplist is ['mango', 'carrot', 'bana']
Mylist is ['carrot', 'bana']
Working principle:
Most of the explanations already exist inProgram. All you need to remember is that if you want to copy a list or similar sequence or other complex objects (not simple objects such as integers), you must use the slice operator to get a copy. If you only want to use another variable name and both names refer to the same object, it may cause various troubles if you are not careful.
Note: Remember that the assignment statement of the list does not create a copy. You must use the slice operator to create a copy of a sequence.
7. More string content
We have discussed strings in detail. What else do we need to know? Then, do you know that the string is also an object and has the same method. These methods can perform various tasks, including checking some strings and removing spaces.
The strings you use in the program areStr
Class Object. Some useful methods of this class are described in the following example. For a complete list of these methods, seeHelp (STR)
.
For example:
# Filename: str_methods.py name = 'swaroop '# This is a string object if name. startswith ('swa'): Print ('yes, the string starts with "SWA" ') If 'A' in name: Print ('yes, it contains the string "A" ') If name. find ('war ')! =-1: Print ('Yes, it contains the string "war" ') delimiter =' _ * _ 'mylist = ['Brazil', 'Russia ', 'India ', 'China'] print (delimiter. join (mylist ))
Output:
C: \ Users \ Administrator> Python D: \ Python \ str_methods.py
Yes, the string starts with "SWA"
Yes, it contains the string ""
Yes, it contains the string "war"
Brazil _ * _ Russia _ * _ India _ * _ China
Working principle:
Here we see the usage of many string methods.
StartswithThe method is used to determine whether a string starts with a specified string. WhileInThe operation checks whether a string is part of another string.
FindThe method is used to find the position of the given string in the string. If the corresponding substring is not found-1.
StrClass also has a simple method to connect each string in the sequence and return the connected stringJoinEach string is separated by a specified string.
Summary:
We have discussed in detail a variety of Python built-in data structures. These data structures will be crucial for programming.
Now we have mastered a lot of basic Python knowledge. Next we will learn how to design and compile a practical Python program.