Python notes (6)

Source: Internet
Author: User

Data Structure

 

I. Introduction

The data structure is basically -- they are structures that can process some data. Or, they are used to store a group of related data.

There are three built-in data structures in Python: List, tuples, and dictionary. We will learn how to use them and how they make programming easier.

Ii. List

List is the data structure that processes a group of ordered projects. You can store a series project in 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. To some extent, it is similar to an array.

For example:

#! /Usr/bin/python <br/> # filename: using_list.py </P> <p> # This is my shopping list <br/> shoplist = ['apple ', 'mango', 'carrot', 'bana'] </P> <p> Print 'I have', Len (shoplist), 'items to purchase. '</P> <p> Print 'these items are:', # notice the comma at end of the line <br/> for item in shoplist: <br/> Print item, </P> <p> Print '\ ni also have to buy rice. '<br/> shoplist. append ('Rice ') <br/> Print 'my shopping list is right ', shoplist </P> <p> Print 'I will sort my list now' <br/> shoplist. sort () <br/> Print 'sorted shopping list is ', shoplist </P> <p> Print 'the first item I will buy is ', shoplist [0] <br/> olditem = shoplist [0] <br/> Del shoplist [0] <br/> Print 'I bought ', olditem <br/> Print 'my shopping list is right', shoplist </P> <p>

Output:

$ Python using_list.py <br/> I have 4 items to purchase. <br/> these items are: apple mango carrot banana <br/> I also have to buy rice. <br/> my shopping list is now ['apple', 'mango ', 'carrot', 'Banana ', 'Rice '] <br/> I will sort my list now <br/> sorted shopping list is ['apple', 'Banana', 'carrot', 'mango ', 'Rice '] <br/> the first item I will buy is apple <br/> I bought the apple <br/> my shopping list is now ['banana ', 'carrot', 'mango', 'Rice '] </P> <p>

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

4. 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 the key must be unique.

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 as follows: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.

Note: Key/value pairs in the dictionary are not ordered. If you want a specific sequence, you should sort them before use.

For example:

#! /Usr/bin/python <br/> # filename: using_dict.py </P> <p> # 'AB' is short for 'A' ddress 'B' ook </P> <p> AB = {'swaroop ': 'swaroopch @ byteofpython.info ', <br/> 'Larry': 'Larry @ wall.org ', <br/> 'matsumo': 'matz @ ruby-lang.org ', <br/> 'pemer ': 'spammer @ hotmail.com '<br/>}</P> <p> Print "swaroop's address is % s" % AB ['swaroop'] </P> <p> # adding a key/value pair <br/> AB ['guid'] = 'guido @ python.org '</P> <p> # deleting a key/value pair <br /> Del AB ['pemer'] </P> <p> Print '\ nthere are % d contacts in the address-book \ n' % Len (AB) <br/> for name, address in AB. items (): <br/> Print 'Contact % s at % s' % (name, address) </P> <p> If 'guid' in AB: # Or AB. has_key ('guido ') <br/> Print "\ nguido's address is % s" % AB ['guido']

V. Sequence

Lists, tuples, and strings are all sequences. 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.

For example:

#! /Usr/bin/python <br/> # filename: seq. PY </P> <p> shoplist = ['apple', 'mango', 'carrot ', 'bana'] </P> <p> # indexing or 'subauthorization' operation <br/> Print 'item 0 is ', shoplist [0] <br/> Print 'item 1 is ', shoplist [1] <br/> Print 'item 2 is ', shoplist [2] <br/> Print 'item 3 is ', shoplist [3] <br/> Print 'item-1 is ', shoplist [-1] <br/> Print 'item-2 is ', shoplist [-2] </P> <p> # Slicing on a list <br/> Print 'item 1 to 3 is ', shoplist [] <br/> Print 'item 2 to end is ', shoplist [2:] <br/> Print 'item 1 to-1 is', shoplist [1: -1] <br/> Print 'item start to end is ', shoplist [:] </P> <p> # Slicing on a string <br/> name = 'swaroop '<br/> Print 'characters 1 to 3 is ', name [] <br/> Print 'characters 2 to end is ', name [2:] <br/> Print 'characters 1 to-1 is', name [1: -1] <br/> Print 'characters start to end is ', name [:] </P> <p>

Output:

$ Python seq. PY <br/> Item 0 is apple <br/> Item 1 is mango <br/> Item 2 is carrot <br/> item 3 is banana <br/> item-1 is banana <br/> item-2 is carrot <br/> item 1 to 3 is ['mango ', 'carrot'] <br/> Item 2 to end is ['carrot', 'bana'] <br/> item 1 to-1 is ['mango ', 'carrot'] <br/> item start to end is ['apple', 'mango', 'carrot ', 'bana'] <br/> characters 1 to 3 is wa <br/> characters 2 to end is aroop <br/> characters 1 to-1 is waroo <br/> characters start to end is swaroop </P> <p>

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.

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

6. Reference

When you create an object and assign it a variable, this variable only references the object, rather than indicates 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.

For example:

#! /Usr/bin/python <br/> # filename: reference. PY </P> <p> Print 'simple assignment '<br/> shoplist = ['apple', 'mango', 'carrot ', 'bana'] <br/> mylist = shoplist # mylist is just another name pointing to the same object! </P> <p> Del shoplist [0] </P> <p> Print 'shoplist is ', shoplist <br/> Print 'mylist is ', mylist <br/> # notice that both shoplist and mylist both print the same list without <br/> # The 'apple' confirming that they point to the same object </P> <p> Print 'Copy by making a full slice '<br/> mylist = shoplist [:] # Make a copy by doing a full slice <br/> Del mylist [0] # Remove first item </P> <p> Print 'shoplist is ', shoplist <br/> Print 'mylist is ', mylist <br/> # notice that now the two lists are different </P> <p>

Output:

$ Python reference. PY <br/> simple assignment <br/> shoplist is ['mango', 'carrot', 'bana'] <br/> mylist is ['mango ', 'carrot', 'bana'] <br/> copy by making a full slice <br/> shoplist is ['mango', 'carrot ', 'bana'] <br/> mylist is ['carrot', 'bana'] </P> <p>

To some extent, it is similar to a pointer in C.

VII. Some Supplements to strings

The strings you use in the program arestrClass Object. Some useful methods of this class are described in the following example. For a complete list of these methods, seehelp(str).

For example:

#! /Usr/bin/python <br/> # filename: str_methods.py </P> <p> name = 'swaroop '# This is a string object </P> <p> If name. startswith ('swa'): <br/> Print 'Yes, the string starts with "SWA" '</P> <p> If 'A' in name: <br/> Print 'Yes, it contains the string "A" '</P> <p> If name. find ('war ')! =-1: <br/> Print 'yes, it contains the string "war" '</P> <p> delimiter =' _ * _ '<br/> mylist = ['Brazil', 'Russia ', 'India ', 'China'] <br/> Print delimiter. join (mylist) </P> <p>

Output:

$ Python str_methods.py <br/> yes, the string starts with "SWA" <br/> yes, it contains the string "A" <br/> yes, it contains the string "war" <br/> Brazil _ * _ Russia _ * _ India _ * _ China </P> <p>

#! /Usr/bin/python <br/> # filename: using_tuple.py </P> <p> zoo = ('Wolf ', 'elephant', 'penguin ') <br/> Print 'number of animals in the zoo is ', Len (zoo) </P> <p> new_zoo = ('monkey', 'dolfen', zoo) <br/> Print 'number of animals in the new zoo is ', Len (new_zoo) <br/> Print 'All animals in new zoo are ', new_zoo <br/> Print 'animals brought from old zoo are ', new_zoo [2] <br/> Print 'last animal brought from old zoo is ', new_zoo [2] [2] </P> <p>

Output:

$ Python using_tuple.py <br/> Number of animals in the zoo is 3 <br/> Number of animals in the new zoo is 3 <br/> all animals in new zoo are (' monkey ', 'dolf', ('Wolf ', 'elephant', 'penguin') <br/> animals brought from old zoo are ('wolves', 'elephant ', 'penguin') <br/> last animal brought from old zoo is Penguin </P> <p>

VariablezooIs a tuples. We can see thatlenThe function can be used to obtain the length of a tuples. This also indicates that the tuples are also a sequence.

Tuples that contain 0 or 1 project. An empty tuples consist of an empty pair of parentheses, suchmyempty = (). 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 to include a project2You should specifysingleton = (2 , ).

For example:

#! /Usr/bin/python <br/> # filename: print_tuple.py </P> <p> age = 22 <br/> name = 'swaroop '</P> <p> Print' % s is % d years old' % (name, age) <br/> Print 'Why is % s playing with that python? '% Name </P> <p>

Output:

$ Python print_tuple.py <br/> swaroop is 22 years old <br/> Why is swaroop playing with that python? </P> <p>

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.