Data structures for Python

Source: Internet
Author: User

The data structure is basically-they are the structures that can handle some data. Alternatively, they are used to store a set of related data. There are three built-in data structures in Python-lists, tuples, and dictionaries.

1. List

A list is a data structure that handles a set of ordered items, that is, you can store a sequence of items in a list. Imagine you have a shopping list that says what you want to buy, and you can easily understand the list. Just on your shopping list, it's possible that everything is on its own, and in Python, you're separating each item with a comma.

The items in the list should be enclosed in square brackets so that Python knows that you are specifying a list. Once you have created a list, you can add, delete, or search for items in the list. Since you can add or delete items, we say that the list is a mutable data type, that is, this type can be changed.

Python provides the Append method for the list class, which allows you to add an item at the end of the listing. For example, the Mylist.append (' an item ') List MyList adds that string. Note that you use the point number to use the object's methods.

#!/usr/bin/python

# Filename:using_list.py

# This is my shopping list

Shoplist = [' Apple ', ' mango ', ' carrot ', ' banana ']

print ' I has ', Len (shoplist), ' items to purchase. '

Print ' These items are: ',

For item in Shoplist:

Print Item,

print ' \ni also has to buy rice. '

Shoplist.append (' rice ')

print ' My shopping list is now ', shoplist

print ' I'll sort my list now '

Shoplist.sort ()

print ' Sorted shopping list is ', shoplist

print ' The first item I'll buy is ', shoplist[0]

Olditem = shoplist[0]

Del Shoplist[0]

print ' I bought the ', Olditem

print ' My shopping list is now ', shoplist

[email protected] code]# python using_list.py

I have 4 items to purchase.

These items are:apple Mango carrot Banana

I also has to buy rice.

My shopping list is now [' Apple ', ' mango ', ' carrot ', ' banana ', ' rice ']

I'll sort my list now

Sorted shopping list is [' Apple ', ' banana ', ' carrot ', ' mango ', ' rice ']

The first item I'll buy is Apple

I bought the apple

My shopping list is now [' banana ', ' carrot ', ' mango ', ' rice ']

The variable shoplist is a list of someone's shopping. In Shoplist, we only store the name strings for what you buy, but remember that you can add any kind of object including numbers or even other lists to the list.

Also used for: In loops recursively between items in the list. From now on, you must have realized that the list is also a sequence.

Notice that a comma is used at the end of the print statement to eliminate the line break that is automatically printed for each print statement. It's a bit ugly, but it's really simple and effective.

Next, you add an item to the list using the Append method, as discussed earlier. We then verify that the item is actually added to the list by printing the contents of the list. The Print list simply passes the list to the print statement, and we can get a neat output.

Next, we 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 differs from how the string works. This is what we call the list to be mutable and the string immutable.

Finally, but when we finished buying something in the market, we wanted to remove it from the list. We use the DEL statement to do the work. Here, we point out which of the items in the list we want to delete, and the Del statement removes it from the list for us. We indicate that we want to delete the first element in the list, so we use del Shoplist[0] (remember, Python counts from 0).

2, meta-group

Tuples and lists are very similar, except that tuples and strings are immutable, meaning that you cannot modify tuples. Tuples are defined by a comma-separated list of items in parentheses. Tuples are typically used when a statement or user-defined function can safely take a set of values, that is, the value of the tuple being used does not change.

Working with tuples:

#!/usr/bin/python

# Filename:using_tuple.py

Zoo = (' 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 is ', New_zoo

print ' Animals brought from the old Zoo is ', new_zoo[2]

print ' Last animal brought from the old Zoo is ', new_zoo[2][2]

[email protected] code]# 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 is (' monkey ', ' Dolphin ', (' Wolf ', ' Elephant ', ' penguin ')

Animals brought from the old Zoo is (' Wolf ', ' Elephant ', ' penguin ')

Last animal brought from the old Zoo is Penguin

Variable Zoo is a tuple, and we see that the Len function can be used to get the length of the tuple. This also indicates that the tuple is also a sequence.

As the old zoo was closed, we moved the animals to the new zoo. Therefore, the New_zoo tuple contains some animals already there and animals brought from the old zoo, noting that tuples within tuples do not lose their identities.

We can access the items in a tuple by using a pair of parentheses to indicate the location of an item, just as we use the list.

This is called the index operator. We use new_zoo[2] to access the third item in the New_zoo. We use new_zoo[2][2] to access the third item of the third project of the New_zoo tuple.

Contains a tuple of 0 or 1 item objectives. An empty tuple consists of a pair of empty parentheses, such as Myempty = (). However, tuples that contain a single element are less simple. You must follow the first (only) item followed by a comma so that python can differentiate between tuples and a Parenthesized object in an expression. That is, if you want a tuple containing item 2, you should indicate Singleton = (2,).

The list in the Perl list loses its identity, that is, the list will be beaten. Tuples in the same tuple, or a tuple in a list, or a list in a tuple, and so on, as long as it's python, they just use objects stored by another object.

The most common usage of tuples is in the print statement, and here is an example:

#!/usr/bin/python

# Filename:print_tuple.py

Age = 22

name = ' RGF '

Print '%s is%d years old '% (name,age)

Print ' Why are%s playing with that python? '% name

[email protected] code]# python print_tuple.py

RGF is from years old

Why are RGF playing with that python?

The print statement can use the string that follows the% symbol for the item tuple. These strings have a custom function. Customization lets the output meet a specific format. The customization can be%s to represent a string or%d to represent an integer. Tuples must correspond to these customizations in the same order.

Observing the first tuple we used, we first used%s, which corresponds to the variable name, which is the first item in the tuple. The second customization is%d, which corresponds to the second item of the tuple, age.

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

This usage of print makes it extremely easy to write output, which avoids many string manipulations. It also avoids the comma that we have been using for a long time.

Most of the time, you can just use the%s customization and let Python take care of the rest. The logarithm of this method also works. However, you may want to use the correct customization so that you can avoid the correctness of one layer of inspection procedures.

In the second print statement, we used a custom, followed by a single item after the% sign-no parentheses (and of course, parentheses). This only works when there is only one customization in the string.

3. Dictionaries

The dictionary is similar to the Address book where you find the address and contact details by contact name, that is, we associate the key (first name) with the value (details). Note that the key 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 keys to the dictionary, but you could make immutable or mutable objects the values of the dictionaries. Basically, you should only use simple objects as keys.

Key-value pairs are tagged in the dictionary in such a way that: 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 braces.

Remember that the key/value pairs in the dictionary are not sequential. If you want a particular order, then you should sort them yourself before using them.

A dictionary is an instance/object of the Dict class.

Use a dictionary:

#!/usr/bin/python

# Filename:using_dict.py

AB = {' RGF ': ' [email protected] ',

' Larry ': ' [email protected] ',

' Matsumoto ': ' [email protected] ',

' Spammer ': ' [email protected] '

}

Print "RGF s address is%s"% ab[' RGF ']

# Adding a Key/value pair

ab[' Xuanxuan ' = ' [email protected] '

# Deleting a Key/value pair

Del ab[' spammer ']

print ' \nthere is%d contacts in the address-book\n '% len (AB)

For name,address in Ab.items ():

print ' Contact%s at%s '% (name,address)

If ' Xuanxuan ' in AB:

Print "\nxuanxuan s address is%s"% ab[' Xuanxuan ']

[email protected] code]# python using_dict.py

RGF ' s address is [email protected]


There is 4 contacts in the Address-book


Contact Matsumoto at [email protected]

Contact Xuanxuan at [email protected]

Contact Larry at [email protected]

Contact RGF at [email protected]


Xuanxuan ' s address is [email protected]

Dictionary AB was created with tags. Key/value pairs are then used to specify the keys using the index operators that have been discussed in the list and tuple chapters. You can use the index operator to address a key and assign it a value, which adds a new key/value pair.

You can use the DEL statement to delete a key/value pair. We just need to specify the dictionary and use the index operator to indicate which keys to delete, and then pass them to the DEL statement. When we do this, we don't need to know the value of that key.

Next, we use the dictionary's items method to use each key/value pair in the dictionary. This returns a list of tuples with each tuple containing a pair of items-the key and the corresponding value. We grab this pair and assign it to for. The variables in the in loop name and address then print the values in the for-block.

You can use the in operator to verify that a key/value pair exists or to use the Has_key method of the Dict class. You can use Help (dict) to view a complete list of methods for the Dict class.

4. Sequence

Lists, tuples, and strings are sequences, but what are the sequences and why are they so special? The two main features of a sequence are index operators and slice operators. The index operator allows us to fetch a specific item from the sequence. The slice operator allows us to get a slice of the sequence, which is part of the sequence.

Use sequence:

#!/usr/bin/python

# Filename:seq.py

Shoplist = [' Apple ', ' mango ', ' carrot ', ' banana ']

# indexing or ' Subscription ' operation

print ' 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 list

print ' Item 1 to 3 is ', Shoplist[1:3]

print ' Item 2 to End ', Shoplist[2:]

print ' Item 1 to-1 is ', shoplist[1:-1]

print ' Item start to End ', shoplist[:]


# slicing on a string

name = ' Rgfxuanxuan '

print ' characters 1 to 3 ', Name[1:3]

print ' characters 2 to end ', Name[2:]

print ' characters 1 to-1 is ', name[1:-1]

print ' characters start to end ', name[:]

[email protected] code]# 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 ', ' banana ']

Item 1 to-1 is [' Mango ', ' carrot ']

Item start to end is [' Apple ', ' mango ', ' carrot ', ' banana ']

Characters 1 to 3 is GF

Characters 2 to end are Fxuanxuan

Characters 1 to-1 is Gfxuanxua

Characters start to end is Rgfxuanxuan

First, let's learn how to use an index to get a single item in a sequence. This is also referred to as subscript operation. Whenever you specify a sequence with a number in square brackets, Python grabs the item in the sequence that corresponds to the position. Remember, Python counts from 0 onwards. Therefore, Shoplist[0] crawls the first item, SHOPLIST[3] fetches the fourth element in the shoplist sequence.

The index can also be negative, in which case the position is calculated from the end of the sequence. Therefore, Shoplist[-1] represents the last element of the sequence and Shoplist[-2] The penultimate item of the crawl sequence.

The slice operator is a sequence name followed by a square bracket, with a pair of optional digits in the square brackets, separated by a colon. Note that this is very similar to the index operator you are using. Remember that the number is optional, and the colon is required.

The first number in the slice operator (preceded by a colon) indicates where the slice begins, and the second number (after the colon) indicates where the slice ends. If you do not specify the first number, Python starts from the beginning of the sequence. If you do not specify a second number, Python stops at the end of the sequence. Note that the returned sequence starts at the start position and ends just before the end position. That is, the start position is contained in the sequence slice, and the end position is excluded from the slice.

Thus, Shoplist[1:3] returns a slice containing two items, starting at position 1, including position 2, but stopping a sequence slice at position 3. Similarly, shoplist[:] Returns a copy of the entire sequence.

You can make slices with negative numbers. Negative numbers are used at the beginning of the end of the sequence. For example, shoplist[:-1] Returns a sequence slice that contains all the items except for the last item.

Use the Python interpreter to interactively try out different slices of the specified combination, i.e. you can see the results immediately at the prompt. The magic of sequences is that you can access tuples, lists, and strings in the same way.

5. Reference

When you create an object and assign a variable to it, the variable simply refers to that object, not the object itself! In other words, the variable name points to the memory of the object stored in your computer. This is called the name-to-object binding.

Generally speaking, you do not need to worry about this, but there are some subtle effects on the reference that need your attention. This is illustrated by the following example.

#!/usr/bin/python

# Filename:reference.py

print ' Simple assignement '

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 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 slice

Del Mylist[0]

# Remove the first item

print ' Shoplist is ', shoplist

print ' MyList is ', mylist

# Notice that now the lists is different

[email protected] code]# python reference.py

Simple assignement

Shoplist is [' Mango ', ' carrot ', ' banana ']

MyList is [' Mango ', ' carrot ', ' banana ']

Copy by making a full slice

Shoplist is [' Mango ', ' carrot ', ' banana ']

MyList is [' carrot ', ' banana ']

If you want to copy a list or similar sequences or other complex objects (not simple objects such as integers), then you must use the slice operator to get the copy. If you just want to use another variable name and all two names refer to the same object, you might get into trouble if you're not careful.

Remember that the assignment statement for the list does not create a copy. You have to use the slice operator to create a copy of the sequence.

Vi. Methods of strings

A string is also an object, with the same method. These methods can complete various tasks, including verifying part of a string and removing whitespace. The strings you use in your program are objects of the Str class. Some useful methods of this class are described in the following example. If you want to know the complete list of these methods, see Help (str).


#!/usr/bin/python

# Filename:str_methods.py

name = ' Swaroop ' # This is a string object

If Name.startwith (' 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)

[email protected] code]# python str_methods.py

Yes,the string starts with "Swa"

Yes,it contains the string "a"

Yes,it contains the string "War"

Brazil_*_russia_*_india_*_china

The StartsWith method is used to test whether a string starts with the given string. The in operator is used to verify that a given string is part of another string.

The Find method is used to find the position of the given string in another string, or 1 to indicate that the substring cannot be found. The Str class also has a neat method for items with a string join sequence as a delimiter, which returns a generated large string.


Data structures for Python

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.