[Python] Getting Started tutorial (5): Data Structure in Python

Source: Internet
Author: User
  • List

List is the data structure that processes a group of ordered projects. You can store a series project in a list. Suppose you have a shopping list that records the items you want to buy, so you can easily understand the list. However, in your shopping table, each item may have a single row, while in Python, you use commas to separate each item.

The items in the list should be included in square brackets so that python knows that you are specifying a list. Once you create a list, you can add, delete, or search for projects in the list. Since you can add or delete a project, we say that the list is a variable data type, that is, this type can be changed.

List is an example of using objects and classes. When you use the variable I and assign values to it, such as assigning an integer 5, you can think that you have created an object (Instance) I of class (type) int. In fact, you can take a look at help (INT) to better understand this.

Classes also have methods, that is, they define local functions for classes only. You can use these functions only when you have an object of this class. For example, Python provides the append method for the list class. This method allows you to add a project at the end of the list. For example, add the string to mylist in mylist. append ('an item') list. Note: Use the dot to use the object method.

A class also has a domain, which is a variable defined only for the class. Only when you have an object of this class can you use these variables/names. Class, for example, mylist. Field.

Usage list
Example 1 usage list

#!/usr/bin/python# 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:') # Notice the comma at end of the linefor item in shoplist:    print(item)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 now', shoplist )

Output
$ 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']

The shoplist variable is a shopping list of someone. In shoplist, we only store the name string of the purchased item, but remember that you can add any types of objects including numbers or other lists to the list.

We also use the for... in loop to recursively iterate between projects in the list. From now on, you must have realized that the list is also a sequence. The sequence features will be discussed in later sections.

Next, use the append method to add a project to the list, as discussed previously. Then, we can print the list to check whether the project has been added to the list. To print a list, simply pass the list to the print statement, and we can get a clean output.

Next, we will use the sort method of the List to sort the list. It should be understood that this method affects the List itself, rather than returning a modified list-this is different from the method used to work with strings. This is what we call the list variable and the string variable.

Finally, we want to delete an item from the list when purchasing it in the market. We use the del statement to complete this task. Here, we point out which project in the list we want to delete, and the del statement is for us to delete it from the list. We specify that we want to delete the first element in the list, so we use del shoplist [0] (counting starts from 0 ).

If you want to know all the methods defined by the list object, you can obtain the complete knowledge through help (list.

  • Tuples

Tuples are similar to lists, except that tuples and strings are immutable, that is, you cannot modify them. The tuples are defined by commas (,) in parentheses. Tuples are usually used to securely use a group of values for statements or user-defined functions. That is, the values of the used tuples do not change.

Use tuples
Example 2 Use tuples

#!/usr/bin/python# Filename: using_tuple.pyzoo = ('wolf', 'elephant', 'penguin')print('Number of animals in the zoo is', len(zoo))new_zoo = ('monkey', 'dolphin', zoo)print('Number of animals 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])


Output
$ Python using_tuple.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolph', ('Wolf ', 'elephant', 'penguin '))
Animals brought from old zoo are ('Wolf ', 'elephant', 'penguin ')
Last animal brought from old zoo is penguin

How it works
The variable zoo is a tuples. We can see that the Len function can be used to obtain the length of the tuples. This also indicates that the tuples are also a sequence.

Since the old zoo was closed, we moved the animals to the new zoo. Therefore, new_zoo tuples contain animals that are already there and that are brought from the old zoo. Back to the topic, note that the tuples in the tuples do not lose their identities.

We can use a pair of square brackets to specify the position of a project to access the project in the tuples, just as we use the list. This is called an index operator. We use new_zoo [2] to access the third project in new_zoo. We use new_zoo [2] [2] to access the third project of the new_zoo tuples.

Tuples that contain 0 or 1 project. An empty tuples consist of an empty pair of parentheses, such as myempty = ().

However, tuples containing a single element are not that simple. You must be followed by a comma in the first (unique) project so that python can distinguish between a tuple and an object with parentheses in the expression. That is, if you want a tuples containing project 2, you should specify Singleton = (2 ,).

Tuples and print statements
The most common usage of tuples is to use them in print statements. The following is an example:

Example 3 Output Using tuples

#!/usr/bin/python# Filename: print_tuple.pyage = 22name = 'Swaroop'print('%s is %d years old' % (name, age))print('Why is %s playing with that python?' % name)


Output
$ Python print_tuple.py
Swaroop is 22 years old
Why is swaroop playing with that python?

How it works
The print statement can use a string of the Project tuples followed by the % symbol. These strings have custom functions. Customization allows the output to meet certain formats. The Value % s indicates a string or % d indicates an integer. Tuples must be customized in the same order.

Observe that we use the first tuples. First, we use % S, which corresponds to the variable name, which is the first item in the tuples. The second customization is % d, which corresponds to the second project age of the tuples.

What Python does here is to convert each item in the tuples into a string and replace the custom position with the string value. Therefore, % s is replaced with the variable name value, and so on.

This usage of print makes writing output extremely simple, which avoids many string operations. It also avoids the comma that we have been using.

Most of the time, you can only use % s for customization, and let Python handle the remaining things. This method also works on the logarithm. However, you may want to use the correct customization to avoid checking whether the program is correct on multiple layers.

In the second print statement, we used a customization, followed by a single project after the % symbol-No parentheses. This is only valid when there is only one custom character string.

  • Dictionary

The dictionary is similar to the address book in which you use the contact name to find the address and contact details. That is, we associate the key (name) and value (details) together. Note that keys must be unique, as if two people happen to have the same name, you cannot find the correct information.

Note that you can only use immutable objects (such as strings) as Dictionary keys, but you can use immutable or variable objects as Dictionary values. Basically, you should only use simple objects as keys.

Key-value pairs are marked in the dictionary in this way: 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 key/value pairs in the dictionary have no order. If you want a specific sequence, you should sort them before use.

A dictionary is an instance/Object of the dict class.

Use dictionaries
Example 4 use a dictionary

#!/usr/bin/python# Filename: using_dict.py# 'ab' is short for 'a'ddress'b'ookab = {       'Swaroop'   : 'swaroopch@byteofpython.info',             'Larry'     : 'larry@wall.org',             'Matsumoto' : 'matz@ruby-lang.org',             'Spammer'   : 'spammer@hotmail.com'     }print("Swaroop's address is %s" % ab['Swaroop'])# Adding a key/value pairab['Guido'] = 'guido@python.org'# Deleting a key/value pairdel ab['Spammer']print('\nThere are %d contacts in the address-book\n' % len(ab))for name, address in ab.items():    print('Contact %s at %s' % (name, address))if 'Guido' in ab: # OR ab.has_key('Guido')    print("\nGuido's address is %s" % ab['Guido'])


Output
$ Python using_dict.py
Swaroop's address is swaroopch@byteofpython.info

There are 4 contacts in the address-book

Contact swaroop at swaroopch@byteofpython.info
Contact Matsumoto at matz@ruby-lang.org
Contact larat larry@wall.org
Contact Guido at guido@python.org

Guido's address is guido@python.org

How it works
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 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 use our old friend -- 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 them to the Del statement. When performing this operation, we do not need to know the value corresponding to that key.

Next, we use the items method of the dictionary 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 it to the variable name and address in the for .. in loop respectively, and then print these values in the for-block.

We can use the in operator to check whether a key/value pair exists, or use the has_key method of the dict class. You can use help (dict) to view the complete list of dict classes.

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


  • 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 Slice operator allows us to obtain a slice of a sequence, that is, a part of the sequence.

Use Sequence
Example 5 use sequence

#!/usr/bin/python# Filename: seq.pyshoplist = ['apple', 'mango', 'carrot', 'banana']# Indexing or 'Subscription' 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])# Slicing on a listprint('Item 1 to 3 is', shoplist[1:3])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 stringname = 'swaroop'print('characters 1 to 3 is', name[1:3])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
$ 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
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

How it works
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.

Use the python interpreter to interactively specify a combination of different slices, that is, you can see the result immediately at the prompt. The magic of sequences is that you can access tuples, lists, and strings in the same way.



  • Reference

When you create an object and assign it a variable, this variable only refers to the object, rather than the object itself! That is to say, the variable name points to the memory of the object stored in your computer. This is called name-to-object binding.

Generally, you don't need to worry about this, but you need to pay attention to some minor effects in reference. This will be illustrated in the following example.

Objects and references
Example 6 objects and references

#!/usr/bin/python# Filename: reference.pyprint('Simple Assignment')shoplist = ['apple', 'mango', 'carrot', 'banana']mylist = shoplist # mylist is just another name pointing to the same object!del shoplist[0]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 objectprint('Copy by making a full slice')mylist = shoplist[:] # make a copy by doing a full slicedel mylist[0] # remove first itemprint('shoplist is', shoplist)print('mylist is', mylist)# notice that now the two lists are different


Output
$ 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']

How it works
Most of the explanations are in the comments of the program. 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.

String
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 are all STR class objects. Some useful methods of this class are described in the following example. For a complete list of these methods, see help (STR ).

String Method
Example 7 string method

#!/usr/bin/python# Filename: str_methods.pyname = 'Swaroop' # This is a string objectif 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
$ 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

How it works
Here, we can see that many string methods are used. The startwith method is used to test whether a string starts with a given string. The in operator is used to check whether a given string is part of another string.

The find method is used to locate a given string in another string, or return-1 to indicate that the substring cannot be found. The STR class also provides a neat Method for items that use a string join sequence as the separator. It returns a large string generated.

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.